<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus04.html">Previous Chapter</a>
    <li> <a href="cplusplus06.html">Next Chapter</a>
</ul>
<hr>
<a name="IOStreams"></a><a name="l62"></a>
<h1>Chapter 5: The IO-stream Library</h1>
<a name="iostreams"></a>

<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="iostreams/intro"></a>As an extension to the standard stream (<a name="an328"></a>
<code>FILE</code>) approach, well known from the
<strong>C</strong> programming language, <strong>C++</strong> offers an <em>input/output</em> (<a name="an329"></a>
I/O)
library <a name="an330"></a>
 based on <code>class</code> concepts.
<p>
Earlier (in chapter <a href="cplusplus03.html#FirstImpression">3</a>) we've already seen examples of the
use of the <strong>C++</strong> I/O library, especially the use of the insertion
operator (<<) and the extraction operator (>>).
In this chapter we'll cover the library in more detail.
<p>
The discussion of input and output facilities provided by the <strong>C++</strong>
programming language heavily uses the <code>class</code> concept, and the notion of
member functions. Although the construction of classes will be covered in the
upcoming chapter <a href="cplusplus06.html#Classes">6</a>, and <em>inheritance</em> will formally be introduced
in chapter <a href="cplusplus13.html#INHERITANCE">13</a>, we think it is well possible to introduce input
and output (I/O) facilities long before the technical background of
these topics is actually covered.
<p>
Most <strong>C++</strong> I/O classes have names starting with <a name="an331"></a>
<code>basic_</code> (like
<code>basic_ios</code>). However, these <a name="an332"></a>
<code>basic_</code> names are not regularly found in
<strong>C++</strong> programs, as most classes are also defined using <a name="an333"></a>
<code>typedef</code>
definitions like:
        <pre>
        typedef basic_ios&lt;char&gt;       ios;
</pre>
    Since <strong>C++</strong> defines both the <a name="an334"></a>
<code>char</code> and <a name="an335"></a>
<code>wchar_t</code> types, I/O
facilities were developed using the <a name="an336"></a>
<em>template</em> mechanism. As will be
further elaborated in chapter <a href="cplusplus18.html#TEMPLATES">18</a>, this way it was possible to
construct <a name="an337"></a>
generic software, which could thereupon be used for both the
<code>char</code> and <code>wchar_t</code> types. So, analogously to the above <code>typedef</code> there
exists a
        <pre>
        typedef basic_ios&lt;wchar_t&gt;    wios;
</pre>
    This type definition can be used for the <code>wchar_t</code> type. Because of the
existence of these type definitions, the <code>basic_</code> prefix can be omitted from
the Annotations without loss of continuity. In the Annotations the emphasis is
primarily on the standard 8-bits <code>char</code> type.
<p>
As a <a name="an338"></a>
side effect to this implementation it must be stressed that it is
<em>not</em> anymore correct to declare iostream objects using standard
    <a name="an339"></a>
forward declarations, like:
        <pre>
    class ostream;          // now erroneous
</pre>
    Instead, sources that must <a name="an340"></a>
declare iostream classes must
    <a name="an341"></a>

        <pre>
    #include &lt;iosfwd&gt;       // correct way to declare iostream classes
</pre>
<p>
Using the <strong>C++</strong> I/O library offers the additional advantage of
    <a name="an342"></a>
<em>type safety</em>. Objects (or plain values) are inserted into
streams. Compare this to the situation commonly encountered in <strong>C</strong> where the
<a name="an343"></a>
<code>fprintf()</code> function is used to indicate by a format string what kind of
value to expect where. Compared to this latter situation <strong>C++</strong>'s
<em>iostream</em> approach immediately uses the objects where their values should
appear, as in
        <pre>
    cout &lt;&lt; "There were " &lt;&lt; nMaidens &lt;&lt; " virgins present\n";
</pre>
The compiler notices the type of the <code>nMaidens</code> variable, inserting
its proper value at the appropriate place in the sentence inserted into
the <code>cout</code> iostream.
<p>
Compare this to the situation encountered in <strong>C</strong>. Although <strong>C</strong> compilers
are getting smarter and smarter over the years, and although a well-designed
<strong>C</strong> compiler may warn you for a mismatch between a format specifier and the
type of a variable encountered in the corresponding position of the argument
list of a <a name="an344"></a>
<code>printf()</code> statement, it can't do much more than <em>warn</em> you.
The <em>type safety</em> seen in <strong>C++</strong> <em>prevents</em> you from making type
mismatches, as there are no types to match.
<p>
Apart from this, <em>iostreams</em> offer more or less the same set of
possibilities as the standard <code>FILE</code>-based I/O used in <strong>C</strong>: files can be
opened, closed, positioned, read, written, etc.. In <strong>C++</strong> the basic <code>FILE</code>
structure, as used in <strong>C</strong>, is still available. <strong>C++</strong> adds I/O based on
classes to <code>FILE</code>-based I/O, resulting in type safety, extensibility, and a
clean design. In the <a name="an345"></a>
ANSI/ISO standard the intent was to construct
architecture independent I/O. Previous implementations of the iostreams
library did not always comply with the standard, resulting in many extensions
to the standard. Software developed earlier may have to be partially rewritten
with respect to I/O. This is tough for those who are now forced to modify
existing software, but every feature and extension that was available in
previous implementations can be reconstructed easily using the ANSI/ISO
standard conforming I/O library. Not all of these reimplementations
can be covered in this chapter, as most use inheritance and polymorphism,
topics that will be covered in chapters <a href="cplusplus13.html#INHERITANCE">13</a> and
<a href="cplusplus14.html#POLYMORPHISM">14</a>, respectively. Selected reimplementations will be provided
in chapter <a href="cplusplus20.html#CONCRETE">20</a>, and below references to particular sections in that
chapter will be given where appropriate.
        <a name="IOCLASSESFIG"></a><p><center><img src="iostreams/ioclasses.gif" align="bottom" alt="Figure 3 is shown here."/><br>
Figure 3: Central I/O Classes
</center><p><br>

This chapter is organized as follows (see also Figure <a href="cplusplus05.html#IOCLASSESFIG">3</a>):
    <ul>
        <li> The <code>class</code> <a name="an346"></a>
<code>ios_base</code> represents the foundation upon with
the iostreams I/O library was built. The
class <code>ios</code> forms the foundation of all I/O operations, and defines, among
other things, the facilities for inspecting the <a name="an347"></a>
state of I/O streams and
    <a name="an348"></a>
output formatting.
        <li> The class <a name="an349"></a>
<code>ios</code> was directly derived from <code>ios_base</code>. Every
class of the I/O library doing input or output is <em>derived</em> from this
<code>ios</code> class, and <em>inherits</em> its (and, by implication, <code>ios_base</code>'s)
capabilities. The reader is urged to keep this feature in mind while reading
this chapter. The concept of inheritance is not discussed further here, but
rather in chapter <a href="cplusplus13.html#INHERITANCE">13</a>.
<p>
An important function of the class <code>ios</code> is to define the communication with
the <a name="an350"></a>
<em>buffer</em> that is used by streams. The buffer is a <a name="an351"></a>
<code>streambuf</code> object
(or is derived from the class <code>streambuf</code>) and is responsible for the actual
input and/or output. This means that <code>iostream</code> objects do not perform
input/output operations themselves, but leave these to the (stream)buffer
objects with which they are associated.
        <li> Next, basic <strong>C++</strong> output facilities are discussed. The basic
class used for output is <a name="an352"></a>
<code>ostream</code>, defining the <a name="an353"></a>
insertion operator as
well as other facilities for writing information to streams. Apart from
inserting information in files it is possible to
    <a name="an354"></a>
insert information in memory buffers, for which the <a name="an355"></a>
<code>ostringstream</code>
class is available. Formatting of the output is to a great extent possible
using the facilities defined in the <code>ios</code> class, but it is also possible to
<a name="an356"></a>
<em>insert formatting commands</em> directly in streams, using
<a name="an357"></a>
<em>manipulators</em>. This aspect of <strong>C++</strong> output is discussed as well.
        <li> Basic <strong>C++</strong> input facilities are available in the <a name="an358"></a>
<code>istream</code>
class. This class defines the <a name="an359"></a>
insertion operator and related facilities for
input. Analogous to the <code>ostringstream</code> a class <a name="an360"></a>
<code>istringstream</code> class is
available for <a name="an361"></a>
extracting information from memory buffers.
        <li> Finally, several advanced I/O-related topics are discussed:
other topics, <a name="an362"></a>
combined reading and writing using streams and
    <a name="an363"></a>
mixing <strong>C</strong> and <strong>C++</strong> I/O using <a name="an364"></a>
<code>filebuf</code> ojects. Other I/O
related topics are covered elsewhere in the Annotations, e.g., in chapter
<a href="cplusplus20.html#CONCRETE">20</a>.
    </ul>
    In the iostream library the stream objects have a limited role: they form
the interface between, on the one hand, the objects to be input or output and,
on the other hand, the <code>streambuf</code>, which is responsible for the actual
input and output to the <a name="an365"></a>
device for which the <code>streambuf</code> object was
created in the first place. This approach allows us to construct a new kind of
<code>streambuf</code> for a new kind of device, and use that streambuf in combination
with the `good old' <code>istream</code>- or <code>ostream</code>-class facilities. It is
important to understand the distinction between the formatting roles of the
iostream objects and the buffering interface to an external device as
implemented in a <code>streambuf</code>. Interfacing to new devices (like <a name="an366"></a>
<em>sockets</em>
or <a name="an367"></a>
<em>file descriptors</em>) requires us to construct a new kind of <code>streambuf</code>,
not a new kind of <code>istream</code> or <code>ostream</code> object. A <a name="an368"></a>
<em>wrapper class</em> may
be constructed around the <code>istream</code> or <code>ostream</code> classes, though, to ease
the access to a special device. This is how the stringstream classes were
constructed.
<p>
<a name="l63"></a>
<h2>5.1: Special header files</h2>
<a name="iostreams/headers"></a>    Several <a name="an369"></a>
header files are defined for the iostream library. Depending on
the situation at hand, the following header files should be used:
    <ul>
    <li><a name="an370"></a>
<code>#include &lt;iosfwd&gt;</code>: sources should use this <a name="an371"></a>
preprocessor directive
if a forward declaration is required for the iostream classes. For example,
if a function defines a reference parameter to an <code>ostream</code> then, when this
function itself is declared, there is no need for the compiler to know exactly
what an <code>ostream</code> is. In the header file declaring such a function the
<code>ostream</code> class merely needs to be be declared. One cannot use
    <pre>
    class ostream;      // erroneous declaration

    void someFunction(ostream &amp;str);
</pre>
    but, instead, one should use:
    <pre>
    #include &lt;iosfwd&gt;   // correctly declares class ostream

    void someFunction(ostream &amp;str);
</pre>
    <li><a name="an372"></a>
<code>#include &lt;streambuf&gt;</code>: sources should use this preprocessor directive
when using <code>streambuf</code> or <a name="an373"></a>
<code>filebuf</code> classes. See sections <a href="cplusplus05.html#STREAMBUF">5.7</a>
and <a href="cplusplus05.html#FILEBUF">5.7.2</a>.
    <li><a name="an374"></a>
<code>#include &lt;istream&gt;</code>: sources should use this preprocessor directive
when using the class <code>istream</code> or when using classes that do both input and
output.  See section <a href="cplusplus05.html#ISTREAM">5.5.1</a>.
    <li><a name="an375"></a>
<code>#include &lt;ostream&gt;</code>: sources should use this <a name="an376"></a>
preprocessor directive
when using the class <a name="an377"></a>
<code>ostream</code> class or when using classes that do both
input and output.  See section <a href="cplusplus05.html#OSTREAM">5.4.1</a>.
    <li><a name="an378"></a>
<code>#include &lt;iostream&gt;</code>: sources should use this preprocessor directive
when using the global stream objects (like <a name="an379"></a>
<code>cin</code> and <a name="an380"></a>
<code>cout</code>).
    <li><a name="an381"></a>
<code>#include &lt;fstream&gt;</code>: sources  should use this preprocessor directive
when using the file stream classes.   See sections <a href="cplusplus05.html#IFSTREAM">5.5.2</a>,
<a href="cplusplus05.html#OFSTREAM">5.4.2</a> and <a href="cplusplus05.html#FSTREAM">5.8.4</a>.
    <li><a name="an382"></a>
<code>#include &lt;sstream&gt;</code>: sources should use this preprocessor directive
when using the string stream classes. See sections <a href="cplusplus05.html#OSTRINGSTREAM">5.4.3</a> and
<a href="cplusplus05.html#ISTRINGSTREAM">5.5.3</a>.
    <li><a name="an383"></a>
<code>#include &lt;iomanip&gt;</code>: sources  should use this preprocessor directive
when using parameterized manipulators. See section <a href="cplusplus05.html#MANIPULATORS">5.6</a>
    </ul>
<p>
<a name="l64"></a>
<h2>5.2: The foundation: the class `ios_base'</h2>
<a name="iostreams/iosbase"></a>The class <a name="an384"></a>
<code>ios_base</code> forms the foundation of all I/O operations, and
defines, among other things, the facilities for inspecting the
    <a name="an385"></a>
state of I/O streams and most <a name="an386"></a>
output formatting facilities. Every
stream class of the I/O library is, via the class <a name="an387"></a>
<code>ios</code>, <em>derived</em> from
this class, and <em>inherits</em> its capabilities.
<p>
The discussion of the class <code>ios_base</code> precedes the introduction of members
that can be used for actual reading from and writing to streams. But as the
<code>ios_base</code> class is the foundation on which all I/O in <strong>C++</strong> was built, we
introduce it as the first class of the <strong>C++</strong> I/O library.
<p>
Note, however, that as in <strong>C</strong>, I/O in <strong>C++</strong> is <em>not</em> part of the
language (although it <em>is</em> part of the <a name="an388"></a>
ANSI/ISO standard on <strong>C++</strong>):
although it is technically possible to ignore all predefined I/O facilities,
nobody actually does so, and the I/O library represents therefore a
<em>de facto</em> I/O standard in <strong>C++</strong>. Also note that, as mentioned before,
the iostream classes do not do input and output themselves, but delegate this
to an auxiliary class: the class <a name="an389"></a>
<code>streambuf</code> or its derivatives.
<p>
For the sake of completeness it is noted that it is <em>not</em>
possible to construct an <code>ios_base</code> object directly. As covered by chapter
<a href="cplusplus13.html#INHERITANCE">13</a>, classes that are derived from <code>ios_base</code> (like <code>ios</code>)
may construct <code>ios_base</code> objects using the <a name="an390"></a>
<code>ios_base::ios_base()</code>
constructor.
<p>
The next class in the iostream hierarchy (see figure <a href="cplusplus05.html#IOCLASSESFIG">3</a>) is the
class <a name="an391"></a>
<code>ios</code>. Since the stream classes inherit from the class <code>ios</code>, and
thus also from <code>ios_base</code>, in practice the distinction between <code>ios_base</code>
and <a name="an392"></a>
<code>ios</code> is hardly important. Therefore, facilities actually provided by
<code>ios_base</code> will be discussed as facilities provided by <code>ios</code>. The reader
who is interested in the true class in which a particular facility is defined
should consult the relevant header files (e.g., <a name="an393"></a>
<code>ios_base.h</code> and
<a name="an394"></a>
<code>basic_ios.h</code>).
<p>
<a name="l65"></a>
<h2>5.3: Interfacing `streambuf' objects: the class `ios'</h2>
<a name="iostreams/ios"></a>The <a name="an395"></a>
<code>ios</code> class was derived directly from <a name="an396"></a>
<code>ios_base</code>, and it defines <em>de
facto</em> the foundation for all stream classes of the <strong>C++</strong> I/O library.
<p>
Although it <em>is</em> possible to construct an <code>ios</code> object
directly, this is hardly ever done. The purpose of the class <code>ios</code> is to
provide the facilities of the class <code>basic_ios</code>, and to add several new
facilites, all related to managing the <code>streambuf</code> object which is managed
by objects of the class <code>ios</code>.
<p>
All other stream classes are either directly or indirectly derived from
<code>ios</code>. This implies, as explained in chapter <a href="cplusplus13.html#INHERITANCE">13</a>, that all
facilities offered by the classes <code>ios</code> and <code>ios_base</code> are also available
in other stream classes. Before discussing these additional stream classes,
the facilities offered by the class <code>ios</code> (and by implication: by
<code>ios_base</code>) are now introduced.
<p>
The class <code>ios</code> offers several member functions, most of which are related
to <a name="an397"></a>
formatting. Other frequently used member functions are:
    <ul>
    <li><a name="an398"></a>
<code>streambuf *ios::rdbuf()</code>:<blockquote>This member function returns a pointer to the <a name="an399"></a>
<code>streambuf</code> object
        forming the interface between the <code>ios</code> object and the <a name="an400"></a>
device
        with which the <code>ios</code> object communicates. See section
        <a href="cplusplus20.html#STRBUF">20.1.2</a> for further information about the <code>class
        streambuf</code>.</blockquote>
    <li><code>streambuf *ios::rdbuf(streambuf *new)</code>:
        <blockquote>This member function can be used to associate a <code>ios</code>
        object with another <code>streambuf</code> object. A pointer to the
        <code>ios</code> object's original <code>streambuf</code> object is returned. The object
        to which this pointer points is not destroyed when the <code>stream</code>
        object goes out of scope, but is owned by the caller of
        <code>rdbuf()</code>.</blockquote>
    <li><a name="an401"></a>
<code>ostream *ios::tie()</code>:<blockquote>This member function returns a pointer to the <a name="an402"></a>
<code>ostream</code> object that
        is currently tied to the <code>ios</code> object (see the next member). The
        returned <code>ostream</code> object is
        <em>flushed</em> every time before information is input or output to the
        <code>ios</code> object of which the <code>tie()</code> member is called. The return
        value 0 indicates that currently no <code>ostream</code> object is tied to
        the <code>ios</code> object. See section <a href="cplusplus05.html#COUPLING">5.8.2</a> for details.</blockquote>
    <li><code>ostream *ios::tie(ostream *new)</code>:
        <blockquote>This member function can be used to associate an <code>ios</code>
        object with another <code>ostream</code> object. A pointer to the
        <code>ios</code> object's original <code>ostream</code> object is returned.
        See section <a href="cplusplus05.html#COUPLING">5.8.2</a> for details.</blockquote>
    </ul>
<p>
<a name="IOSTATES"></a><a name="l66"></a>
<h3>5.3.1: Condition states</h3>
    <a name="iostreams/conditions"></a>Operations on streams may succeed and they may fail for several reasons.
Whenever an operation fails, further read and write operations on the stream
are suspended. It is possible to inspect (and possibly: clear) the
    <a name="an403"></a>
condition state of streams, so that a program can repair the problem,
instead of having to abort.
<p>
Conditions are represented by the following <a name="an404"></a>
<em>condition flags</em>:
    <ul>
        <li><a name="an405"></a>
<code>ios::badbit</code>:
            <blockquote>if this flag has been raised an illegal operation has been
requested  at the level of the <code>streambuf</code> object to which the stream
interfaces. See the member functions below for some examples.</blockquote>
        <li><a name="an406"></a>
<code>ios::eofbit</code>:
            <blockquote>if this flag has been raised, the <code>ios</code> object has sensed
end of file.</blockquote>
        <li><a name="an407"></a>
<code>ios::failbit</code>:
            <blockquote>if this flag has been raised, an operation performed by the
stream object has failed (like an attempt to extract an <code>int</code> when no
numeric characters are available on input). In this case the stream itself
could not perform the operation that was requested of it.</blockquote>
        <li><a name="an408"></a>
<code>ios::goodbit</code>:
            <blockquote>this flag is raised when  none of the other three condition
flags were raised.</blockquote>
    </ul>
<p>
Several <a name="an409"></a>
condition member functions are available to manipulate or
determine the states of <code>ios</code> objects. Originally they returned <code>int</code>
values, but their current return type is <code>bool</code>:
    <ul>
    <li><a name="an410"></a>
<code>ios::bad()</code>:
            <blockquote>this member function returns <code>true</code> when
<code>ios::badbit</code> has been set and <code>false</code> otherwise.  If <code>true</code> is
returned it indicates that an illegal operation has been requested at the
level of the <code>streambuf</code> object to which the stream interfaces. What does
this mean? It indicates that the <code>streambuf</code> itself is behaving
unexpectedly. Consider the following example:
        <pre>
    std::ostream error(0);
</pre>
    This constructs an <code>ostream</code> object <em>without</em> providing it with a
working <code>streambuf</code> object. Since this `<code>streambuf</code>' will never operate
properly, its <code>ios::badbit</code> is raised from the very beginning:
<code>error.bad()</code> returns <code>true</code>.
            </blockquote>
    <li><a name="an411"></a>
<code>ios::eof()</code>:
            <blockquote>this member function returns <code>true</code> when end of file
(<code>EOF</code>) has been sensed (i.e., <code>ios::eofbit</code> has been set) and
<code>false</code> otherwise. Assume we're reading lines line-by-line from <code>cin</code>,
but the last line is not terminated by a final <code>\n</code> character. In that case
<code>getline()</code>, attempting to read the <code>\n</code> delimiter, hits end-of-file
first. This sets <code>eos::eofbit</code>, and <code>cin.eof()</code> returns
<code>true</code>. For example, assume <code>main()</code> executes the statements:
        <pre>
    getline(cin, str);
    cout &lt;&lt; cin.eof();
</pre>
    Following:
        <pre>
    echo "hello world" | program
</pre>
    the value 0 (no EOF sensed) is printed, following:
        <pre>
    echo -n "hello world" | program
</pre>
    the value 1 (EOF sensed) is printed.</blockquote>
    <li><a name="an412"></a>
<code>ios::fail()</code>:
            <blockquote>this member function returns <code>true</code> when ios::bad()
returns <code>true</code> or when the ios::failbit was set, and <code>false</code> otherwise.
In the above example, <code>cin.fail()</code> returns <code>false</code>, whether we
terminate the final line with a delimiter or not (as we've read a
line). However, trying to execute a second <code>getline()</code> statement will set
<code>ios::failbit</code>, causing <code>cin::fail()</code> to return <code>true</code>. The value <code>not
fail()</code> is returned by the <code>bool</code> interpretation of a stream object (see
below).</blockquote>
    <li><a name="an413"></a>
<code>ios::good()</code>:
            <blockquote>this member function returns the value of the
<code>ios::goodbit</code> flag. It returns <code>true</code> when none of the other
condition flags (<code>ios::badbit, ios::eofbit, ios::failbit</code>) were raised.
    Consider the following little program:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;

    using namespace std;

    void state()
    {
        cout &lt;&lt; "\n"
                "Bad: " &lt;&lt; cin.bad() &lt;&lt; " "
                "Fail: " &lt;&lt; cin.fail() &lt;&lt; " "
                "Eof: " &lt;&lt; cin.eof() &lt;&lt; " "
                "Good: " &lt;&lt; cin.good() &lt;&lt; endl;
    }

    int main()
    {
        string line;
        int x;

        cin &gt;&gt; x;
        state();

        cin.clear();
        getline(cin, line);
        state();

        getline(cin, line);
        state();
    }
</pre>
        When this program processes a file having two lines, containing,
respectively, <code>hello</code> and <code>world</code>, while the second
line is not terminated by a <code>\n</code> character it shows the following results:
        <pre>
    Bad: 0 Fail: 1 Eof: 0 Good: 0

    Bad: 0 Fail: 0 Eof: 0 Good: 1

    Bad: 0 Fail: 0 Eof: 1 Good: 0
</pre>
        So, extracting <code>x</code> fails (<code>good()</code> returning <code>false</code>). Then, the
error state is cleared, and the first line is successfully read (<code>good()</code>
returning <code>true</code>). Finally the second line is read (incompletely):
<code>good()</code> returns t(false), and <code>eof()</code> returns <code>true</code>.
        </blockquote>
    <li> <a name="an414"></a>

         <a name="an415"></a>

         <a name="an416"></a>

        Interpreting streams as <code>bool</code> values:
            <blockquote>streams may be used in expressions expecting logical
values. Some examples are:
        <pre>
    if (cin)                // cin itself interpreted as bool
    if (cin &gt;&gt; x)           // cin interpreted as bool after an extraction
    if (getline(cin, str))  // getline returning cin
</pre>
        When interpreting a stream as a logical value, it is actually <code>not
ios::fail()</code> that is interpreted. So, the above examples may be rewritten as:
        <pre>
    if (not cin.fail())
    if (not (cin &gt;&gt; x).fail())
    if (not getline(cin, str).fail())
</pre>
    The former incantation, however, is used almost exclusively.
            </blockquote>
    </ul>
<p>
The following members are available to manage error states:
    <ul>
        <li><a name="an417"></a>
<code>ios::clear()</code>:
    <blockquote>When an error condition has occurred, and the condition can be
repaired, then <code>clear()</code> can be called to clear the error status of the
file. An overloaded version accepts state flags, which are set after first
clearing the current set of flags: <code>ios::clear(int state)</code>. It's return type
is <code>void</code></blockquote>
        <li><a name="an418"></a>
<code>ios::rdstate()</code>:
        <blockquote><a name="an419"></a>

    <a name="an420"></a>

    This member function returns (as an <code>int</code>) the current set of flags that
are set for an <code>ios</code> object. To test for a particular flag, use the
<a name="an421"></a>
bitwise and operator:
        <pre>
    if (iosObject.rdstate() &amp; ios::good)
    {
        // state is good
    }
</pre>
        </blockquote>
        <li> <a name="an422"></a>

            <a name="an423"></a>
 <a name="an424"></a>
<code>ios::setstate(int flags)</code>:
        <blockquote><a name="an425"></a>

    This member is used to <em>set</em> a particular set of flags. Its return type
is <code>void</code>. The member <code>ios::clear()</code> is a shortcut to clear all error
flags.  Of course, clearing the flags doesn't automatically mean the
error condition has been cleared too. The strategy should be:
        <ul>
            <li> An error condition is detected,
            <li> The error is repaired
            <li> The member <code>ios::clear()</code> is called.
        </ul>
        </blockquote>
    </ul>
    <strong>C++</strong> supports an <a name="an426"></a>
<em>exception</em> mechanism for handling exceptional
situations. According to the <a name="an427"></a>
ANSI/ISO standard, exceptions can be used
with stream objects. Exceptions are covered in chapter <a href="cplusplus08.html#EXCEPTIONS">8</a>. Using
exceptions with stream objects is covered in section <a href="cplusplus08.html#IOEXCEPTIONS">8.7</a>.
<p>
<a name="l67"></a>
<h3>5.3.2: Formatting output and input</h3>
    <a name="iostreams/formatting"></a>The way information is written to streams (or, occasionally, read from
streams) may be controlled by <a name="an428"></a>
<em>formatting flags</em>.
<p>
Formatting is used when it is necessary to control the width of an output
field or an input buffer and if formatting is used to determine the form
(e.g., the <a name="an429"></a>
<em>radix</em>) in which a value is displayed. Most formatting belongs
to the realm of the <code>ios</code> class, although most formatting is actually used
with output streams, like the upcoming <code>ostream</code> class. Since the formatting
is controlled by flags, defined in the <code>ios</code> class, it was
considered best to discuss formatting with the <code>ios</code> class itself, rather
than with a selected derived class, where the choice of the derived class
would always be somewhat arbitrarily.
<p>
Formatting is controlled by a set of <a name="an430"></a>
<em>formatting flags</em>. These flags can
basically be altered in two ways: using specialized member functions,
discussed in section <a href="cplusplus05.html#FORMATMEMBERS">5.3.2.2</a> or using <em>manipulators</em>, which are
directly inserted into streams. Manipulators are not applied directly to the
<code>ios</code> class, as they require the use of the insertion operator. Consequently
they are discussed later (in section <a href="cplusplus05.html#MANIPULATORS">5.6</a>).
<p>
<a name="FORMATFLAGS"></a><a name="l68"></a>
<strong>5.3.2.1: Formatting flags</strong>
        <a name="iostreams/flags"></a>Most <a name="an431"></a>
<em>formatting flags</em> are related to outputting information. Information
can be written to output streams in basically two ways: <a name="an432"></a>
<em>binary output</em>
will write information directly to the output stream, without conversion to
some <a name="an433"></a>
human-readable format. E.g., an <code>int</code> value is written as a set of
four bytes. Alternatively, <a name="an434"></a>
<em>formatted output</em> will convert the values that
are stored in bytes in the computer's memory to <a name="an435"></a>
ASCII-characters, in order
to create a human-readable form.
<p>
Formatting flags can be used to define the way this conversion takes place, to
control, e.g., the number of characters that are written to the output
stream.
<p>
The following formatting flags are available (see also sections
<a href="cplusplus05.html#FORMATMEMBERS">5.3.2.2</a> and <a href="cplusplus05.html#MANIPULATORS">5.6</a>):
    <ul>
        <li><a name="an436"></a>
<code>ios::adjustfield</code>:
            <blockquote><a name="an437"></a>
<em>mask value</em> used in combination with a flag setting
defining the way values are adjusted in wide fields (<code>ios::left</code>,
<code>ios::right</code>, <code>ios::internal</code>). Example, setting the value 10 left-aligned
in a field of 10 character positions:
                <pre>
    cout.setf(ios::left, ios::adjustfield);
    cout &lt;&lt; "'" &lt;&lt; setw(10) &lt;&lt; 10 &lt;&lt; "'" &lt;&lt; endl;
</pre>
            </blockquote>
        <li><a name="an438"></a>
<code>ios::basefield</code>:
            <blockquote><a name="an439"></a>
<em>mask value</em> used in combination with a flag setting the
radix of integral values to output (<code>ios::dec</code>, <code>ios::hex</code> or
<code>ios::oct</code>). Example, printing the value 57005 as a hexadecimal number:
                <pre>
    cout.setf(ios::hex, ios::basefield);
    cout &lt;&lt; 57005 &lt;&lt; endl;
        // or, using the manipulator:
    cout &lt;&lt; hex &lt;&lt; 57005 &lt;&lt; endl;
</pre>
        </blockquote>
        <li><a name="an440"></a>
<code>ios::boolalpha</code>:
            <blockquote>to display boolean values as text, using the text
`<code>true</code>' for the <code>true</code> logical value, and the string `<code>false</code>' for
the <code>false</code> logical value. By default this flag is not set. Corresponding
manipulators: <code>boolalpha</code> and <a name="an441"></a>
<code>noboolalpha</code>. Example, printing the
boolean value `true' instead of 1:
                <pre>
    cout &lt;&lt; boolalpha &lt;&lt; (1 == 1) &lt;&lt; endl;
</pre>
</blockquote>
        <li><a name="an442"></a>
<code>ios::dec</code>:
            <blockquote>to read and display integral values as decimal (i.e.,
<a name="an443"></a>
radix 10) values. This is the default.
    With <code>setf()</code> the mask value <a name="an444"></a>
<code>ios::basefield</code> must be provided.
    Corresponding manipulator: <a name="an445"></a>
<code>dec</code>.</blockquote>
        <li><a name="an446"></a>
<code>ios::fixed</code>:
            <blockquote>to display real values in a fixed notation (e.g.,
            12.25), as opposed to displaying values in a scientific
notation. If just a change of notation is requested the  mask value
<a name="an447"></a>
<code>ios::floatfield</code> must be provided when <code>setf()</code> is used. Example:
see <code>ios::scientific</code> below. Corresponding manipulator: <code>fixed</code>.
<p>
Another use of <code>ios::fixed</code> is to set a fixed number of digits behind
the decimal point when floating or double values are to be printed. See
<code>ios::precision</code> in section <a href="cplusplus05.html#FORMATMEMBERS">5.3.2.2</a>.
            </blockquote>
        <li><a name="an448"></a>
<code>ios::floatfield</code>:
            <blockquote>mask value used in combination with a flag setting the
way real numbers are displayed (<code>ios::fixed</code> or
<code>ios::scientific</code>). Example:
                <pre>
    cout.setf(ios::fixed, ios::floatfield);
</pre>
            </blockquote>
        <li><a name="an449"></a>
<code>ios::hex</code>:
            <blockquote>to read and display integral values as hexadecimal values
(i.e., radix 16) values.
    With <code>setf()</code> the mask value <a name="an450"></a>
<code>ios::basefield</code> must be provided.
    Corresponding manipulator: <a name="an451"></a>
<code>hex</code>.</blockquote>
        <li><a name="an452"></a>
<code>ios::internal</code>:
            <blockquote>to add <a name="an453"></a>
fill characters (blanks by default) between the
minus sign of negative numbers and the value itself.
    With <code>setf()</code> the mask value <a name="an454"></a>
<code>adjustfield</code> must be provided.
    Corresponding manipulator: <a name="an455"></a>
<code>internal</code>.</blockquote>
        <li><a name="an456"></a>
<code>ios::left</code>:
            <blockquote> to left-adjust (integral) values in fields that are wider
than needed to display the values.  By default values are right-adjusted (see
below).
    With <code>setf()</code> the mask value <a name="an457"></a>
<code>adjustfield</code> must be provided.
    Corresponding manipulator: <a name="an458"></a>
<code>left</code>.</blockquote>
        <li><a name="an459"></a>
<code>ios::oct</code>:
            <blockquote> to display integral values as octal values (i.e., radix 8)
values.
    With <code>setf()</code> the mask value <a name="an460"></a>
<code>ios::basefield</code> must be provided.
    Corresponding manipulator: <a name="an461"></a>
<code>oct</code>.</blockquote>
        <li><a name="an462"></a>
<code>ios::right</code>:
            <blockquote> to right-adjust (integral) values in fields that
are wider than needed to display the values.  This is the default adjustment.
    With <code>setf()</code> the mask value <a name="an463"></a>
<code>adjustfield</code> must be provided.
    Corresponding manipulator: <a name="an464"></a>
<code>right</code>.</blockquote>
        <li><a name="an465"></a>
<code>ios::scientific</code>:
            <blockquote> to display real values in <a name="an466"></a>
<em>scientific notation</em> (e.g.,
1.24e+03).
    With <code>setf()</code> the mask value <a name="an467"></a>
<code>ios::floatfield</code> must be provided.
    Corresponding manipulator: <code>scientific</code>.</blockquote>
        <li><a name="an468"></a>
<code>ios::showbase</code>:
            <blockquote> to display the numeric base of integral
values. With hexadecimal values the <code>0x</code> prefix is used, with octal values
the prefix <code>0</code>. For the (default) decimal value no particular prefix is
used. Corresponding manipulators: <code>showbase</code> and <a name="an469"></a>
<code>noshowbase</code></blockquote>
        <li><a name="an470"></a>
<code>ios::showpoint</code>:
            <blockquote> display a trailing decimal point and trailing
decimal zeros when real numbers are displayed. When this flag is set, an
insertion like:
        <pre>
        cout &lt;&lt; 16.0 &lt;&lt; ", " &lt;&lt; 16.1 &lt;&lt; ", " &lt;&lt; 16 &lt;&lt; endl;
</pre>
    could result in:
        <pre>
        16.0000, 16.1000, 16
</pre>
    Note that the last <code>16</code> is an integral rather than a real number, and is
not given a decimal point: <code>ios::showpoint</code> has no effect here.
    If <code>ios::showpoint</code> is not used, then trailing zeros are discarded. If
the decimal part is zero, then the decimal point is discarded as well.
    Corresponding manipulator: <a name="an471"></a>
<code>showpoint</code>.</blockquote>
        <li><a name="an472"></a>
<code>ios::showpos</code>:
            <blockquote>display a <code>+</code> character with positive
values. Corresponding manipulator: <a name="an473"></a>
<code>showpos</code>.</blockquote>
        <li><a name="an474"></a>
<code>ios::skipws</code>:
            <blockquote>used for extracting information from
streams. When this flag is set (which is the default) leading <a name="an475"></a>
white space
characters (blanks, tabs, newlines, etc.) are skipped when a value is
extracted from a stream. If the flag is not set, leading white space
characters are not skipped.</blockquote>
        <li><a name="an476"></a>
<code>ios::unitbuf</code>:
            <blockquote>flush the stream after each output operation.</blockquote>
        <li><a name="an477"></a>
<code>ios::uppercase</code>:
            <blockquote>use capital letters in the representation of
(hexadecimal or scientifically formatted) values.</blockquote>
    </ul>
<p>
<a name="FORMATMEMBERS"></a><a name="l69"></a>
<strong>5.3.2.2: Format modifying member functions</strong>
        <a name="iostreams/formatmembers"></a>Several <em>member functions</em> are available for I/O <a name="an478"></a>
formatting. Often,
corresponding <a name="an479"></a>
<em>manipulators</em> exist, which may directly be inserted into or
extracted from streams using insertion or extraction operators. See section
<a href="cplusplus05.html#MANIPULATORS">5.6</a> for a discussion of the available manipulators.
They are:
    <ul>
    <li><a name="an480"></a>
<code>ios &amp;copyfmt(ios &amp;obj)</code>:<blockquote>This member function copies
all format definitions from <code>obj</code> to the current <code>ios</code> object. The current
<code>ios</code> object is returned.</blockquote>
    <li><a name="an481"></a>
<code>ios::fill() const</code>:<blockquote>returns (as <code>char</code>) the
current padding character. By default, this is the blank space.</blockquote>
    <li><code>ios::fill(char padding)</code>:
            <blockquote>redefines the padding character. Returns (as <code>char</code>) the
<em>previous</em> padding character. Corresponding manipulator: <a name="an482"></a>
<code>setfill()</code>.</blockquote>
    <li> <a name="an483"></a>
 <code>ios::flags() const</code>:
            <blockquote> returns the current collection of flags controlling the
format state of the stream for which the member function is called. To inspect
a particular flag, use the <a name="an484"></a>
binary and operator, e.g.,
            <pre>
        if (cout.flags() &amp; ios::hex)
        {
            // hexadecimal output of integral values
        }
</pre>
</blockquote>
    <li><code>ios::flags(fmtflags flagset)</code>:
            <blockquote> returns the <em>previous</em> set of flags, and defines the
current set of flags as <code>flagset</code>, defined by a combination of formatting
flags, combined by the <a name="an485"></a>
binary or operator. Note: when setting flags using
    <a name="an486"></a>
 this member, a previously set
flag may have to be unset first. For example, to change the number conversion
of <code>cout</code> from decimal to hexadecimal using this member, do:
        <pre>
cout.flags(ios::hex | cout.flags() &amp; ~ios::dec);
</pre>
    Alternatively, either of the following statements could have been used:
        <pre>
    cout.setf(ios::hex, ios::basefield);
    cout &lt;&lt; hex;
</pre>
            </blockquote>
    <li> <a name="an487"></a>
 <code>ios::precision() const</code>:
            <blockquote> returns (as <code>int</code>) the number of <a name="an488"></a>
significant digits
used for outputting real values (default: 6).</blockquote>
    <li><code>ios::precision(int signif)</code>:
            <blockquote> redefines the number of significant digits used for
outputting real values, returns (as <code>int</code>) the previously used number of
significant digits. Corresponding manipulator: <a name="an489"></a>
<code>setprecision()</code>. Example,
    <a name="an490"></a>

    <a name="an491"></a>

    <a name="an492"></a>

    <a name="an493"></a>

rounding all displayed double values to a fixed number of digits (e.g., 3)
behind the decimal point:
            <pre>
    cout.setf(ios::fixed);
    cout.precision(3);
    cout &lt;&lt; 3.0 &lt;&lt; " " &lt;&lt; 3.01 &lt;&lt; " " &lt;&lt; 3.001 &lt;&lt; endl;
    cout &lt;&lt; 3.0004 &lt;&lt; " " &lt;&lt; 3.0005 &lt;&lt; " " &lt;&lt; 3.0006 &lt;&lt; endl;
</pre>
    Note that the value 3.0005 is rounded away from zero to 3.001 (-3.0005 is
rounded to -3.001).
        </blockquote>
    <li> <a name="an494"></a>
  <a name="an495"></a>
<code>ios::setf(fmtflags flags)</code>:
            <blockquote> returns the <em>previous</em> set of <em>all</em> flags, and sets
one or more formatting flags (using the bitwise <a name="an496"></a>
<code>operator|()</code> to combine
multiple flags. Other flags are not affected). Corresponding manipulators:
<a name="an497"></a>
<code>setiosflags</code> and <a name="an498"></a>
<code>resetiosflags</code></blockquote>
    <li><code>ios::setf(fmtflags flags, fmtflags mask)</code>:
            <blockquote>returns the <em>previous</em> set of <em>all</em> flags, clears all
flags mentioned in <code>mask</code>, and sets the flags specified in
<code>flags</code>. Well-known mask values are <a name="an499"></a>
<code>ios::adjustfield</code>,
<a name="an500"></a>
<code>ios::basefield</code> and <a name="an501"></a>
<code>ios::floatfield</code>. For example:
        <ul>
            <li><code>setf(ios::left, ios::adjustfield)</code> <a name="an502"></a>

        is used to left-adjust wide values in their field.
(alternatively, <a name="an503"></a>
<code>ios::right</code> and <a name="an504"></a>
<code>ios::internal</code> can be used).
            <li><code>setf(ios::hex, ios::basefield)</code> <a name="an505"></a>

        is used to activate the hexadecimal representation of integral values
(alternatively, <a name="an506"></a>
<code>ios::dec</code> and <a name="an507"></a>
<code>ios::oct</code> can be used).
            <li><code>setf(ios::fixed, ios::floatfield)</code> <a name="an508"></a>

        is used to activate the fixed value representation of real values
(alternatively, <a name="an509"></a>
<code>ios::scientific</code> can be used).
        </ul></blockquote>
    <li> <a name="an510"></a>
 <code>ios::unsetf(fmtflags flags)</code>:
            <blockquote> returns the <em>previous</em> set of <em>all</em> flags, and clears
the specified formatting flags (leaving the remaining flags unaltered). The
unsetting of an active default flag (e.g., <code>cout.unsetf(ios::dec)</code>) has
no effect.</blockquote>
    <li><a name="an511"></a>
<code>ios::width() const</code>:<blockquote> returns (as <code>int</code>) the current
output field width (the number of characters to write for numerical values on
the next insertion operation). Default: 0, meaning `as many characters as
needed to write the value'. Corresponding manipulator: <a name="an512"></a>
<code>setw()</code>.</blockquote>
    <li><code>ios::width(int nchars)</code>:
            <blockquote> returns (as <code>int</code>) the previously used output field
width, redefines the value to <code>nchars</code> for the next insertion
operation. Note that the field width is reset to 0 after every insertion
operation, and that <code>width()</code> currently has no effect on text-values like
<code>char *</code> or <code>string</code> values. Corresponding manipulator: <a name="an513"></a>
<code>setw(int)</code>.</blockquote>
    </ul>
<p>
<a name="l70"></a>
<h2>5.4: Output</h2>
<a name="iostreams/output"></a>In <strong>C++</strong> <a name="an514"></a>
output is primarily based on the <a name="an515"></a>
<code>ostream</code> class. The
<code>ostream</code> class defines the basic operators and members for inserting
information into streams: the <a name="an516"></a>
<em>insertion operator</em> (<<), and
special members like <code>ostream::write()</code> for writing unformatted information
from streams.
<p>
From the class <code>ostream</code> several other classes are derived, all having the
functionality of the <code>ostream</code> class, and adding their own specialties. In
the next sections on `output' we will introduce:
    <ul>
    <li> The class <code>ostream</code>, offering the basic facilities for doing output;
    <li> The class <a name="an517"></a>
<code>ofstream</code>, allowing us to open files for writing
(comparable to <strong>C</strong>'s <a name="an518"></a>
 <code>fopen(filename, "w")</code>);
    <li> The class <a name="an519"></a>
<code>ostringstream</code>, allowing us to write information to
memory rather than to files (streams) (comparable to <strong>C</strong>'s <a name="an520"></a>
<code>sprintf()</code>
function).
    </ul>
<p>
<a name="OSTREAM"></a><a name="l71"></a>
<h3>5.4.1: Basic output: the class `ostream'</h3>
    <a name="iostreams/ostream"></a>The class <a name="an521"></a>
<code>ostream</code> is the class defining basic output facilities. The
<a name="an522"></a>
<code>cout</code>, <a name="an523"></a>
<code>clog</code> and <a name="an524"></a>
<code>cerr</code> objects are all <code>ostream</code> objects. Note that
all facilities defined in the <code>ios</code> class, as far as output is concerned, is
available in the <code>ostream</code> class as well, due to the inheritance mechanism
(discussed in chapter <a href="cplusplus13.html#INHERITANCE">13</a>).
<p>
We can construct <code>ostream</code> objects using the following
    <a name="an525"></a>
<em>ostream constructor</em>:
    <ul>
        <li><code>ostream object(streambuf *sb)</code>:
            <blockquote>this constructor can be used to construct a wrapper around
an existing <code>streambuf</code>, which may be the interface to an existing file. See
chapter <a href="cplusplus20.html#CONCRETE">20</a> for examples.</blockquote> What this boils down to is that it isn't
possible to construct a plain <code>ostream</code> object that can be used for
insertions. When <code>cout</code> or its friends is used, we are actually using a
predefined <code>ostream</code> object that has already been created for us, and
interfaces to, e.g., the standard output stream using a (also predefined)
<code>streambuf</code> object handling the actual interfacing.
<p>
Note that it <em>is</em> possible to construct an <code>ostream</code> object passing it
a ih(std::ostream: constructed using a 0-pointer) 0-pointer as a
<code>streambuf</code>. Such an object cannot be used for insertions (i.e., it will
raise its <code>ios::bad</code> flag when something is inserted into it), but since it
may be given a <code>streambuf</code> later, it may be preliminary constructed,
receiving its <code>streambuf</code> once it becomes available.
    </ul>
    In order to use the <code>ostream</code> class in <strong>C++</strong> sources, the
    <a name="an526"></a>
<code>#include &lt;ostream&gt;</code> <a name="an527"></a>
preprocessor directive must be given. To use the
predefined <code>ostream</code> objects, the <a name="an528"></a>
<code>#include &lt;iostream&gt;</code> preprocessor
directive must be given.
<p>
<a name="l72"></a>
<strong>5.4.1.1: Writing to `ostream' objects</strong>
        <a name="iostreams/ostreamwrite"></a>The class <a name="an529"></a>
<code>ostream</code> supports both formatted and <a name="an530"></a>
<em>binary output</em>.
<p>
The <a name="an531"></a>
<em>insertion operator</em> (<<) may be used to insert values in
a <a name="an532"></a>
type safe way into <code>ostream</code> objects.  This is called
    <a name="an533"></a>
formatted output, as binary values which are stored in the computer's
memory are converted to human-readable <a name="an534"></a>
ASCII characters according to
certain formatting rules.
<p>
Note that the insertion operator points to the <code>ostream </code>object wherein the
information must be inserted.  The normal associativity of <<
remains unaltered, so when a statement like
        <pre>
    cout &lt;&lt; "hello " &lt;&lt; "world";
</pre>
    is encountered, the leftmost two operands are evaluated first (<code>cout</code>
<< <code>"hello "</code>), and an <code>ostream &amp;</code> object, which is actually the
same <code>cout</code> object, is returned. Now, the statement is reduced to
        <pre>
    cout &lt;&lt; "world";
</pre>
    and the second string is inserted into <code>cout</code>.
<p>
The << operator has a lot of (overloaded) variants, so many types of
variables can be inserted into <code>ostream</code> objects. There is an overloaded
<<-operator expecting an <code>int</code>, a <code>double</code>, a pointer, etc. etc..
For every part of the information that is inserted into the stream the operator
returns the <code>ostream</code> object into which the information so far was inserted,
and the next part of the information to be inserted is processed.
<p>
Streams do not have facilities for formatted output like <strong>C</strong>'s
<a name="an535"></a>
<code>form()</code> and <a name="an536"></a>
<code>vform()</code> functions. Although it is not difficult to realize
these facilities in the world of streams, <code>form()</code>-like functionality is
hardly ever required in <strong>C++</strong> programs. Furthermore, as it is potentially
type-<em>unsafe</em>, it might be better to avoid this functionality completely.
<p>
When <a name="an537"></a>
 binary files must be written, normally no
text-formatting is used or required: an <code>int</code> value should be written as a
series of unaltered bytes, not as a series of <a name="an538"></a>
ASCII numeric characters 0 to
9. The following member functions of <code>ostream</code> objects may be used to
write `binary files':
    <ul>
        <li> <a name="an539"></a>
 <code>ostream&amp; ostream::put(char c)</code>:
            <blockquote>This member function writes a single character to the output
stream. Since a character is a byte, this member function could also be used
for writing a single character to a <a name="an540"></a>
 text-file.</blockquote>
        <li> <a name="an541"></a>

            <code>ostream&amp; ostream::write(char const *buffer, int length)</code>:
            <blockquote>This member function writes at most <code>len</code> bytes, stored
in the <code>char const *buffer</code> to the <code>ostream</code> object. The bytes are written
as they are stored in the buffer, no formatting is done whatsoever. Note that
the first argument is a <code>char const *</code>: a <em>type_cast</em> is required to write
any other type. For example, to write an <code>int</code> as an unformatted
series of byte-values:
        <pre>
    int x;
    out.write(reinterpret_cast&lt;char const *&gt;(&amp;x), sizeof(int));
</pre>
        </blockquote>
    </ul>
<p>
<a name="OSTREAMPOS"></a><a name="l73"></a>
<strong>5.4.1.2: `ostream' positioning</strong>
        <a name="iostreams/ostreamseek"></a>Although not every <code>ostream</code> object supports <a name="an542"></a>
repositioning, they usually
do. This means that it is possible to rewrite a section of the stream which
was written earlier. Repositioning is frequently used in
    <a name="an543"></a>
<em>database applications</em> where it must be possible to access the
information in the database randomly.
<p>
The following members are available:
    <ul>
        <li><a name="an544"></a>
<code>pos_type ostream::tellp()</code>:
            <blockquote>this function returns the current (absolute) position where
the next write-operation to the stream will take place. For all practical
purposes a <a name="an545"></a>
<code>pos_type</code> can be considered to be an <code>unsigned long</code>.</blockquote>
        <li><a name="an546"></a>
<code>ostream &amp;ostream::seekp(off_type step, ios::seekdir org)</code>:
            <blockquote>This member function can be used to reposition the
stream. The function expects an <a name="an547"></a>
<code>off_type</code> <code>step</code>, the stepsize in bytes
to go from <code>org</code>. For all practical purposes a <code>off_type</code> can be
considered to be a <code>long</code>.
    The origin of the step, <code>org</code> is an <a name="an548"></a>
<code>ios::seekdir</code> value. Possible
values are:
        <ul>
        <li><a name="an549"></a>
<code>ios::beg</code>:
            <blockquote><code>org</code> is interpreted as the stepsize relative to the
beginning of the stream. If <code>org</code> is not specified, <code>ios::beg</code> is
used. </blockquote>
        <li><a name="an550"></a>
<code>ios::cur</code>:
            <blockquote><code>org</code> is interpreted as the stepsize relative to the
current position (as returned by <code>tellp()</code> of the stream).</blockquote>
        <li><a name="an551"></a>
<code>ios::end</code>:
            <blockquote><code>org</code> is interpreted as the stepsize relative to the
current end position of the the stream.</blockquote>
    </ul>
    It is ok to <a name="an552"></a>
seek beyond end of file<a name="an553"></a>
.
Writing bytes to a location beyond <code>EOF</code> will pad the intermediate bytes
with <a name="an554"></a>
ASCII-Z values: <a name="an555"></a>
null-bytes. It is <em>not</em> allowed to
    <a name="an556"></a>
seek before begin of file.  Seeking before <code>ios::beg</code> will cause the
<a name="an557"></a>
<code>ios::fail</code> flag to be set.
        </blockquote>
    </ul>
<p>
<a name="l74"></a>
<strong>5.4.1.3: `ostream' flushing</strong>
        <a name="iostreams/ostreamflush"></a>Unless the <a name="an558"></a>
<code>ios::unitbuf</code> flag has been set, information written to an
<code>ostream</code> object is not immediately written to the physical stream. Rather,
an internal buffer is filled up during the write-operations, and when full it
is flushed.
<p>
The <a name="an559"></a>
internal buffer can be flushed under program control:
    <ul>
    <li><a name="an560"></a>
<code>ostream&amp; ostream::flush()</code>:
            <blockquote>
    this member function writes any buffered information to the <code>ostream</code>
object. The call to <code>flush()</code> is implied when:
        <ul>
        <li> The <code>ostream</code> object ceases to exist,
        <li> The <code>endl</code> or <code>flush</code> <em>manipulators</em> (see section
            <a href="cplusplus05.html#MANIPULATORS">5.6</a>) are inserted into the <code>ostream</code> object,
        <li> A stream derived from <code>ostream</code> (like <code>ofstream</code>, see section
            <a href="cplusplus05.html#OFSTREAM">5.4.2</a>) is closed.
        </ul>
        </blockquote>
    </ul>
<p>
<a name="OFSTREAM"></a><a name="l75"></a>
<h3>5.4.2: Output to files: the class `ofstream'</h3>
    <a name="iostreams/ofstream"></a>The <a name="an561"></a>
<code>ofstream</code> class is derived from the <code>ostream</code> class: it has the same
capabilities as the <code>ostream</code> class, but can be used to <a name="an562"></a>
access files or
<a name="an563"></a>
create files for writing.
<p>
In order to use the <code>ofstream</code> class  in <strong>C++</strong> sources, the
    <a name="an564"></a>
preprocessor directive <a name="an565"></a>
<code>#include &lt;fstream&gt;</code> must be given. After
including <code>fstream</code> <a name="an566"></a>
 <code>cin</code>, <code>cout</code> etc. are
not automatically declared. If these latter objects are needed too, then
<code>iostream</code> should be included.
<p>
The following <a name="an567"></a>
 constructors are available for
<code>ofstream</code> objects:
    <ul>
        <li><code>ofstream object</code>:
            <blockquote>This is the basic constructor. It creates
an <code>ofstream</code> object which may be associated with an actual file later,
using the <code>open()</code> member (see below).</blockquote>
        <li><code>ofstream object(char const *name, int mode)</code>:
            <blockquote> This constructor can be used to associate an <code>ofstream</code>
object with the file named <code>name</code>, using output mode <code>mode</code>.  The
<a name="an568"></a>
<em>output mode</em> is by default <a name="an569"></a>
<code>ios::out</code>. See section <a href="cplusplus05.html#OUTPUTMODES">5.4.2.1</a> for
a complete overview of available output modes.
<p>
In the following example an <code>ofstream</code> object, associated with the newly
created file <code>/tmp/scratch</code>, is constructed:
        <pre>
    ofstream out("/tmp/scratch");
</pre>
            </blockquote>
    </ul>
    Note that it is not possible to open a <code>ofstream</code> using a
        <a name="an570"></a>
<em>file descriptor</em>. The reason for this is (apparently) that file
descriptors are not universally available over different operating systems.
Fortunately, file descriptors can be used (indirectly) with a <a name="an571"></a>
<code>streambuf</code>
object (and in some implementations: with a <a name="an572"></a>
<code>filebuf</code> object, which is also
a <code>streambuf</code>). <code>Streambuf</code> objects are discussed in section
<a href="cplusplus05.html#STREAMBUF">5.7</a>, <code>filebuf</code> objects are discussed in section <a href="cplusplus05.html#FILEBUF">5.7.2</a>.
<p>
Instead of directly associating an <code>ofstream</code> object with a file, the
object can be constructed first, and opened later.
    <ul>
        <li><a name="an573"></a>
<code>void ofstream::open(char const *name, int mode)</code>:<blockquote>Having constructed an <code>ofstream</code> object, the member
function <code>open()</code> can be used to associate the <code>ofstream</code> object
with an actual file.</blockquote>
        <li><a name="an574"></a>
<code>ofstream::close()</code>:
            <blockquote>Conversely, it is possible to close an <code>ofstream</code> object
explicitly using the <code>close()</code> member function. The function sets the
<a name="an575"></a>
<code>ios::fail</code> flag of the closed object. Closing the file will flush any
buffered information to the associated file. A file is <a name="an576"></a>

automatically closed when the associated <code>ofstream</code> object ceases to exist.</blockquote>
    </ul>
    A subtlety is the following: Assume a stream is constructed, but it is not
actually attached to a file. E.g., the statement <code>ofstream ostr</code> was
executed. When we now check its status through <code>good()</code>, a non-zero (i.e.,
<em>ok</em>) value will be returned.  The `good' status here indicates that the
stream object has been properly constructed. It doesn't mean the file is also
open. To test whether a stream is actually open, <a name="an577"></a>

inspect <a name="an578"></a>
 <code>ofstream::is_open()</code>: If <a name="an579"></a>
<code>true</code>, the stream is
open. See the following example:
        <pre>
    #include &lt;fstream&gt;
    #include &lt;iostream&gt;

    using namespace std;

    int main()
    {
        ofstream of;

        cout &lt;&lt; "of's open state: " &lt;&lt; boolalpha &lt;&lt; of.is_open() &lt;&lt; endl;

        of.open("/dev/null");       // on Unix systems

        cout &lt;&lt; "of's open state: " &lt;&lt; of.is_open() &lt;&lt; endl;
    }
    /*
        Generated output:
    of's open state: false
    of's open state: true
    */
</pre>
<p>
<a name="OUTPUTMODES"></a><a name="l76"></a>
<strong>5.4.2.1: Modes for opening stream objects</strong>
        <a name="iostreams/outmodes"></a>The following <a name="an580"></a>
file modes or <a name="an581"></a>
file flags are defined for constructing or
opening <code>ofstream</code> (or <code>istream</code>, see section <a href="cplusplus05.html#IFSTREAM">5.5.2</a>) objects. The
values are of type <a name="an582"></a>
<code>ios::openmode</code>:
        <ul>
        <li><a name="an583"></a>
<code>ios::app</code>:
            <blockquote> reposition to the end of the file before every output
command. The existing contents of the file are kept.</blockquote>
        <li><a name="an584"></a>
<code>ios::ate</code>:
            <blockquote>Start initially at the end of the file.  The existing
contents of the file are kept.<br>
    Note that the original contents are <em>only</em> kept if some other flag tells
the object to do so. For example <code>ofstream out("gone", ios::ate)</code> will
    <a name="an585"></a>

    <em>rewrite</em> the file <code>gone</code>, because the implied <code>ios::out</code> will cause
the rewriting. If rewriting of an existing file should be prevented, the
<code>ios::in</code> <a name="an586"></a>
 mode should be specified too. Note
that in this case the construction only succeeds if the file already exists.</blockquote>
        <li><a name="an587"></a>
<code>ios::binary</code>:
            <blockquote>open a <a name="an588"></a>
binary file (used on systems which make a
distinction between text- and binary files, like <a name="an589"></a>
MS-DOS or <a name="an590"></a>
MS-Windows).</blockquote>
        <li><a name="an591"></a>
<code>ios::in</code>:
            <blockquote> open the file for reading. The file must exist.</blockquote>
        <li><a name="an592"></a>
<code>ios::out</code>:
            <blockquote> open the file. Create it if it doesn't yet exist. If it
exists, the <a name="an593"></a>
file is rewritten.</blockquote>
        <li><a name="an594"></a>
<code>ios::trunc</code>:
            <blockquote>Start initially with an empty file.  Any existing contents
of the file are lost.</blockquote>
        </ul>
    The following combinations of file flags have special meanings:
        <pre>
    out | app:          The file is created if non-existing,
                        information is always added to the end of the
                        stream;
    out | trunc:        The file is (re)created empty to be written;
    in | out:           The stream may be read and written. However, the
                        file must exist.
    in | out | trunc:   The stream may be read and written. It is
                        (re)created empty first.
</pre>
<p>
<a name="OSTRINGSTREAM"></a><a name="l77"></a>
<h3>5.4.3: Output to memory: the class `ostringstream'</h3>
    <a name="iostreams/ostringstream"></a>In order to <a name="an595"></a>
 write information to memory, using the
<code>stream</code> facilities, <a name="an596"></a>
<code>ostringstream</code> objects can be used. These objects
are derived from <code>ostream</code> objects. The following constructors and members
are available:
    <ul>
        <li><a name="an597"></a>
<code>ostringstream ostr(string const &amp;s, ios::openmode mode)</code>:<blockquote>When using this constructor, the last or both arguments may be
omitted. There is also a constructor requiring only an <a name="an598"></a>
<code>openmode</code>
parameter. If <code>string s</code> is specified and <code>openmode</code> is <code>ios::ate</code>, the
<code>ostringstream</code> object is initialized with the <code>string s</code> and remaining
insertions are appended to the contents of the <code>ostringstream</code> object.  If
<code>string s</code> is provided, it will not be altered, as any information inserted
into the object is stored in dynamically allocated memory which is deleted
when the <code>ostringstream</code> object goes out of scope.</blockquote>
        <li><a name="an599"></a>
<code>string ostringstream::str() const</code>:
            <blockquote>This member function will return the string that is stored
inside the <code>ostringstream</code> object.</blockquote>
        <li><a name="an600"></a>
<code>ostringstream::str(string)</code>:
            <blockquote>This member function will re-initialize the
<code>ostringstream</code> object with new initial contents.</blockquote>
    </ul>
    Before the <code>stringstream</code> class was available the class <a name="an601"></a>
<code>ostrstream</code>
was commonly used for doing output to memory. This latter class suffered from
the fact that, once its contents were retrieved using its <code>str()</code> member
function, these contents were `frozen', meaning that its dynamically allocated
memory was not released when the object went out of scope.  Although this
situation could be prevented (using the <code>ostrstream</code> member call
<a name="an602"></a>
<code>freeze(0)</code>), this implementation could easily lead to <a name="an603"></a>

<em>memory leaks</em>. The <code>stringstream</code> class does not suffer from these
risks. Therefore, the use of the class <code>ostrstream</code> is now deprecated in
favor of <code>ostringstream</code>.
<p>
The following example illustrates the use of the <code>ostringstream</code> class:
several values are inserted into the object. Then, the stored text is stored
in a string, whose length and contents are thereupon printed.  Such
    <code>ostringstream</code> objects are most often used for doing `type to string'
    <a name="an604"></a>
conversions, like converting <code>int</code> to <code>string</code>. Formatting commands
can be used with <code>stringstreams</code> as well, as they are available in
    <code>ostream</code> objects.
    
    Here is an
example showing the use of an <code>ostringstream</code> object:
    <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    #include &lt;sstream&gt;
    #include &lt;fstream&gt;

    using namespace std;

    int main()
    {
        ostringstream ostr("hello ", ios::ate);

        cout &lt;&lt; ostr.str() &lt;&lt; endl;

        ostr.setf(ios::showbase);
        ostr.setf(ios::hex, ios::basefield);
        ostr &lt;&lt; 12345;

        cout &lt;&lt; ostr.str() &lt;&lt; endl;

        ostr &lt;&lt; " -- ";
        ostr.unsetf(ios::hex);
        ostr &lt;&lt; 12;

        cout &lt;&lt; ostr.str() &lt;&lt; endl;
    }
    /*
        Output from this program:
    hello
    hello 0x3039
    hello 0x3039 -- 12
    */
</pre>
<p>
<a name="l78"></a>
<h2>5.5: Input</h2>
<a name="iostreams/input"></a>In <strong>C++</strong> <a name="an605"></a>
input is primarily based on  the <a name="an606"></a>
<code>istream</code> class. The
<code>istream</code> class defines the basic operators and members for extracting
information from streams: the <a name="an607"></a>
<em>extraction operator</em> (>>), and
special members like <code>istream::read()</code> for reading unformatted information
from streams.
<p>
From the class <code>istream</code> several other classes are derived, all having the
functionality of the <code>istream</code> class, and adding their own specialties. In
the next sections we will introduce:
    <ul>
    <li> The class <code>istream</code>, offering the basic facilities for doing input;
    <li> The class <a name="an608"></a>
<code>ifstream</code>, allowing us to open files for reading
(comparable to <strong>C</strong>'s <a name="an609"></a>
 <code>fopen(filename, "r")</code>);
    <li> The class <a name="an610"></a>
<code>istringstream</code>, allowing us to read information from
text that is not stored on files (streams) but in memory (comparable to
<strong>C</strong>'s <a name="an611"></a>
<code>sscanf()</code> function).
    </ul>
<p>
<a name="ISTREAM"></a><a name="l79"></a>
<h3>5.5.1: Basic input: the class `istream'</h3>
    <a name="iostreams/istream"></a>The class <a name="an612"></a>
<code>istream</code> is the I/O class defining basic input facilities. The
<a name="an613"></a>
<code>cin</code> object is an <code>istream</code> object that is declared when sources contain
the <a name="an614"></a>
preprocessor directive <a name="an615"></a>
<code>#include &lt;iostream&gt;</code>. Note that
all facilities defined in the <code>ios</code> class are, as far as input is concerned,
available in the <code>istream</code> class as well due to the inheritance mechanism
(discussed in chapter <a href="cplusplus13.html#INHERITANCE">13</a>).
<p>
<code>Istream</code> objects can be constructed using the following
    <a name="an616"></a>
<em>istream constructor</em>:
    <ul>
        <li><code>istream object(streambuf *sb)</code>:
            <blockquote>this constructor can be used to construct a wrapper around
an existing open stream, based on an existing <code>streambuf</code>, which may be the
interface to an existing file. Similarly to <code>ostream</code> objects, <code>istream</code>
objects may ih(std::istream: constructed using a 0-pointer) initially be
constructed using a 0-pointer. See section <a href="cplusplus05.html#OSTREAM">5.4.1</a> for a discussion, and
chapter <a href="cplusplus20.html#CONCRETE">20</a> for examples.</blockquote>
    </ul>
    In order to use the <code>istream</code> class in <strong>C++</strong> sources, the
    <a name="an617"></a>
<code>#include &lt;istream&gt;</code> <a name="an618"></a>
preprocessor directive must be given. To use the
predefined <code>istream</code> object <a name="an619"></a>
<code>cin</code>, the <a name="an620"></a>
<code>#include &lt;iostream&gt;</code>
preprocessor directive must be given.
<p>
<a name="ISTREAMREAD"></a><a name="l80"></a>
<strong>5.5.1.1: Reading from `istream' objects</strong>
        <a name="iostreams/istreamread"></a>The class <a name="an621"></a>
<code>istream</code> supports both formatted and unformatted
    <a name="an622"></a>
<em>binary input</em>.  The <a name="an623"></a>
<em>extraction operator</em> (<a name="an624"></a>
<code>operator&gt;&gt;()</code>) may be
used to extract values in a <a name="an625"></a>
type safe way from <code>istream</code> objects.  This
is called <a name="an626"></a>
formatted input, whereby human-readable <a name="an627"></a>
ASCII characters are
converted, according to certain formatting rules, to binary values which are
stored in the computer's memory.
<p>
Note that the extraction operator points to the objects or variables which
must receive new values.  The normal associativity of >>
remains unaltered, so when a statement like
        <pre>
    cin &gt;&gt; x &gt;&gt; y;
</pre>
    is encountered, the leftmost two
operands are evaluated first (<code>cin</code> >> <code>x</code>), and an <code>istream &amp;</code>
object, which is actually the same <code>cin</code> object, is returned. Now, the
statement is reduced to
        <pre>
    cin &gt;&gt; y
</pre>
    and the <code>y</code> variable is extracted from <code>cin</code>.
<p>
The >> operator has a lot of (overloaded) variants, so many types of
variables can be extracted from <code>istream</code> objects. There is an overloaded
>> available for the extraction of an <code>int</code>, of a <code>double</code>,
of a string, of an array of characters, possibly to a pointer,
etc. etc.. String or character array extraction <a name="an628"></a>

<a name="an629"></a>
 will (by default) skip all white space characters, and
will then extract all consecutive non-white space characters. After processing
an extraction operator, the <code>istream</code> object into which the information so
far was inserted is returned, which will thereupon be used as the <em>lvalue</em>
for the remaining part of the statement.
<p>
Streams do not have facilities for formatted input (like <strong>C</strong>'s
<a name="an630"></a>
<code>scanf()</code> and <a name="an631"></a>
<code>vscanf()</code> functions). Although it is not difficult to make
these facilities available in the world of streams, <code>scanf()</code>-like
functionality is hardly ever required in <strong>C++</strong> programs. Furthermore, as it
is potentially type-<em>unsafe</em>, it might be better to avoid this functionality
completely.
<p>
When <a name="an632"></a>
 binary files must be read, the information should
normally not be formatted: an <code>int</code> value should be read as a series of
unaltered bytes, not as a series of <a name="an633"></a>
ASCII numeric characters 0 to 9. The
following member functions for reading information from <code>istream</code> objects
are available:
    <ul>
        <li><a name="an634"></a>
<code>int istream::gcount()</code>:
            <blockquote>this function does not actually read from the input stream,
but returns the number of characters that were read from the input stream
during the last unformatted input operation.</blockquote>
        <li><a name="an635"></a>
<code>int istream::get()</code>:
            <blockquote>this function returns <code>EOF</code> or reads and returns the
next available single character as an <code>int</code> value.</blockquote>
        <li><code>istream &amp;istream::get(char &amp;c)</code>:
            <blockquote>this function reads the next single character from the input
stream into <code>c</code>. As its return value is the stream itself, its return value
can be queried to determine whether the extraction succeeded or not.</blockquote>
        <li><code>istream&amp; istream::get(char *buffer, int len [, char delim])</code>:
            <blockquote>This function reads a series of <code>len - 1</code> characters from
the input stream into the array starting at <code>buffer</code>, which should be at
least <code>len</code> bytes long. At most <code>len - 1</code> characters are read into the
buffer. By default, the delimiter is a newline (<code>'\n'</code>) character.  The
delimiter itself is <em>not removed</em> from the input stream.
<p>
After reading the series of characters into <code>buffer</code>, an <a name="an636"></a>
<code>ASCII-Z</code>
character is written beyond the last character that was written to <code>buffer</code>.
The functions <code>eof()</code> and <code>fail()</code> (see section
<a href="cplusplus05.html#IOSTATES">5.3.1</a>) return 0 (<code>false</code>) if the delimiter was not
encountered before <code>len - 1</code> characters were read.  Furthermore, an
<code>ASCII-Z</code> can be used for the delimiter: this way strings terminating in
<code>ASCII-Z</code> characters may be read from a (binary) file. The program using
this <code>get()</code> member function should know in advance the maximum number of
characters that are going to be read.
        </blockquote>
        <li><a name="an637"></a>
<code>istream&amp; istream::getline(char *buffer, int len [, char delim])</code>:
            <blockquote>This function operates analogously to the previous <code>get()</code>
member function, but <code>delim</code> is removed from the stream if it is
actually encountered. At most <code>len - 1</code> bytes are written into the
<code>buffer</code>, and a trailing <code>ASCII-Z</code> character is appended to the string
that was read. The delimiter itself is <em>not</em> stored in the <code>buffer</code>. If
<code>delim</code> was <em>not</em> found (before reading <code>len - 1</code> characters)
the <code>fail()</code> member function, and possibly also
<code>eof()</code> will return true. Note that the <code>std::string</code> class also has a
support function <code>getline()</code> which is used more often than this
<code>istream::getline()</code> member function (see section <a href="cplusplus04.html#STRINGMEMBERS">4.2.4</a>).</blockquote>
        <li><a name="an638"></a>
<code>istream&amp; istream::ignore(int n , int delim)</code>:
            <blockquote>This member function has two (optional) arguments. When
called without arguments, one character is skipped from the
input stream. When called with one argument, <code>n</code> characters are skipped. The
optional second argument specifies a delimiter: after skipping <code>n</code> or the
<code>delim</code> character (whichever comes first) the function returns.</blockquote>
        <li><a name="an639"></a>
<code>int istream::peek()</code>:
            <blockquote>this function returns the next available input character,
but does not actually remove the character from the input stream.</blockquote>
        <li><a name="an640"></a>
<code>istream&amp; istream::putback (char c)</code>:
            <blockquote>The character <code>c</code> that was last read from the stream is
`pushed back' into the input stream, to be read again as the next
character. <code>EOF</code> is returned if this is not allowed. Normally, one
character may always be put back. Note that <code>c</code> <em>must</em> be the character
that was last read from the stream. Trying to put back any other character
will fail.</blockquote>
        <li><a name="an641"></a>
<code>istream&amp; istream::read(char *buffer, int len)</code>:
            <blockquote>This function reads at most <code>len</code> bytes from the input
stream into the buffer. If <code>EOF</code> is encountered first, fewer bytes are
read, and the member function <code>eof()</code> will return <code>true</code>. This function
will normally be used for reading <em>binary</em> files. Section <a href="cplusplus05.html#IFSTREAM">5.5.2</a>
contains an example in which this member function is used. The member function
<code>gcount()</code> should be used to determine the number of characters that were
retrieved by the <code>read()</code> member function.
        </blockquote>
        <li><a name="an642"></a>
<code>istream&amp; istream::readsome(char *buffer, int len)</code>:
            <blockquote>This function reads at most <code>len</code> bytes from the input
stream into the buffer. All available characters are read into the buffer, but
if <code>EOF</code> is encountered first, fewer bytes are
read, without setting the <code>ios_base::eofbit</code> or <code>ios_base::failbit</code>.
        </blockquote>
        <li><a name="an643"></a>
<code>istream&amp; istream::unget()</code>:
            <blockquote>an attempt is made to push back the last character that was
read into the stream. Normally, this succeeds if requested only once after a
read operation, as is the case with <code>putback()</code></blockquote>
    </ul>
<p>
<a name="ISTREAMPOS"></a><a name="l81"></a>
<strong>5.5.1.2: `istream' positioning</strong>
        <a name="iostreams/istreamseek"></a>Although not every <code>istream</code> object supports <a name="an644"></a>
repositioning, some do. This
means that it is possible to read the same section of a stream
repeatedly. Repositioning is frequently used in <a name="an645"></a>
<em>database applications</em>
where it must be possible to access the information in the database randomly.
<p>
The following members are available:
    <ul>
        <li><a name="an646"></a>
<code>pos_type istream::tellg()</code>:
            <blockquote>this function returns the current (absolute) position where
the next read-operation to the stream will take place. For all practical
purposes a <a name="an647"></a>
<code>pos_type</code> can be considered to be an <code>unsigned long</code>.</blockquote>
        <li><a name="an648"></a>
<code>istream &amp;istream::seekg(off_type step, ios::seekdir org)</code>:<blockquote>This member function can be used to reposition the
stream. The function expects an <a name="an649"></a>
<code>off_type</code> <code>step</code>, the stepsize in bytes
to go from <code>org</code>. For all practical purposes a <code>pos_type</code> can be
considered to be a <code>long</code>.
    The origin of the step, <code>org</code> is a <a name="an650"></a>
<code>ios::seekdir</code> value. Possible
values are:
        <ul>
        <li><a name="an651"></a>
<code>ios::beg</code>:
            <blockquote><code>org</code> is interpreted as the stepsize relative to the
beginning of the stream. If <code>org</code> is not specified, <code>ios::beg</code> is
used. </blockquote>
        <li><a name="an652"></a>
<code>ios::cur</code>:
            <blockquote><code>org</code> is interpreted as the stepsize relative to the
current position (as returned by <code>tellg()</code> of the stream).</blockquote>
        <li><a name="an653"></a>
<code>ios::end</code>:
            <blockquote><code>org</code> is interpreted as the stepsize relative to the
current end position of the the stream.</blockquote>
    </ul>
    While it is ok to <a name="an654"></a>
seek beyond end of file, reading at that point
will of course fail.  It is <em>not</em> allowed to <a name="an655"></a>
seek before begin of file.
Seeking before <code>ios::beg</code> will cause the <a name="an656"></a>
<code>ios::fail</code> flag to be set.
        </blockquote>
    </ul>
<p>
<a name="IFSTREAM"></a><a name="l82"></a>
<h3>5.5.2: Input from streams: the class `ifstream'</h3>
    <a name="iostreams/ifstream"></a>The class <a name="an657"></a>
<code>ifstream</code> is derived from the class <code>istream</code>: it has the same
capabilities as the <code>istream</code> class, but can be used to <a name="an658"></a>
access files for
reading. Such files must exist.
<p>
In order to use the <code>ifstream</code> class in <strong>C++</strong> sources, the
    <a name="an659"></a>
preprocessor directive <a name="an660"></a>
<code>#include &lt;fstream&gt;</code> must be given.
<p>
The following <a name="an661"></a>
 constructors are available for
<code>ifstream</code> objects:
    <ul>
        <li><code>ifstream object</code>:
            <blockquote>This is the basic constructor. It creates
an <code>ifstream</code> object which may be associated with an actual file later,
using the <code>open()</code> member (see below).</blockquote>
        <li><code>ifstream object(char const *name, int mode)</code>:
            <blockquote> This constructor can be used to associate an <code>ifstream</code>
object with the file named <code>name</code>, using input mode <code>mode</code>.  The
<a name="an662"></a>
<em>input mode</em> is by default <a name="an663"></a>
<code>ios::in</code>. See also section <a href="cplusplus05.html#OUTPUTMODES">5.4.2.1</a>
for an overview of available file modes.
<p>
In the following example an <code>ifstream</code> object is opened for reading. The
file must exist:
        <pre>
    ifstream in("/tmp/scratch");
</pre>
        </blockquote>
    </ul>
    Instead of directly associating an <code>ifstream</code> object with a file, the
object can be constructed first, and opened later.
    <ul>
        <li><a name="an664"></a>
<code>void ifstream::open(char const *name, int mode)</code>:
            <blockquote> Having constructed an <code>ifstream</code> object, the member
function <code>open()</code> can be used to associate the <code>ifstream</code> object
with an actual file.</blockquote>
        <li><a name="an665"></a>
<code>ifstream::close()</code>:
            <blockquote>Conversely, it is possible to close an <code>ifstream</code> object
explicitly using the <code>close()</code> member function. The function sets the
<a name="an666"></a>
<code>ios::fail</code> flag of the closed object. A file is <a name="an667"></a>

automatically closed when the associated <code>ifstream</code> object ceases to exist.</blockquote>
        </ul>
    A subtlety is the following: Assume a stream is constructed, but it is not
actually attached to a file. E.g., the statement <code>ifstream ostr</code> was
executed. When we now check its status through <code>good()</code>, a non-zero (i.e.,
<em>ok</em>) value will be returned.  The `good' status here indicates that the
stream object has been properly constructed. It doesn't mean the file is also
open. To test whether a stream is actually open, <a name="an668"></a>

inspect <a name="an669"></a>
 <code>ifstream::is_open()</code>: If <a name="an670"></a>
<code>true</code>, the stream is
open. See also the example in section <a href="cplusplus05.html#OFSTREAM">5.4.2</a>.
<p>
To illustrate reading from a binary file (see also section <a href="cplusplus05.html#ISTREAMREAD">5.5.1.1</a>),
a <code>double</code> value is read in binary form from a
file in the next example:
        <pre>
    #include &lt;fstream&gt;
    using namespace std;

    int main(int argc, char **argv)
    {
        ifstream f(argv[1]);
        double   d;

        // reads double in binary form.
        f.read(reinterpret_cast&lt;char *&gt;(&amp;d), sizeof(double));
    }
</pre>
<p>
<a name="ISTRINGSTREAM"></a><a name="l83"></a>
<h3>5.5.3: Input from memory: the class `istringstream'</h3>
    <a name="iostreams/istringstream"></a>In order to <a name="an671"></a>
 read information from memory, using the
<code>stream</code> facilities, <a name="an672"></a>
<code>istringstream</code> objects can be used. These objects
are derived from <code>istream</code> objects. The following constructors and members
are available:
    <ul>
        <li><a name="an673"></a>
<code>istringstream istr</code>:
            <blockquote>The constructor will construct an empty <code>istringstream</code>
object. The object may be filled with information to be extracted later.</blockquote>
        <li><code>istringstream istr(string const &amp;text)</code>:
            <blockquote>The constructor will construct an <code>istringstream</code>
object initialized with the contents of the string <code>text</code>.</blockquote>
        <li><a name="an674"></a>
<code>void istringstream::str(string const &amp;text)</code>:
            <blockquote>This member function will store the contents of the string
<code>text</code> into the <code>istringstream</code> object, overwriting its current contents.</blockquote>
    </ul>
<p>
The <code>istringstream</code> object is commonly used for <a name="an675"></a>

converting <code>ASCII</code> text to its binary equivalent, like the <strong>C</strong> function
<a name="an676"></a>
<code>atoi()</code>. The following example illustrates the use of the <code>istringstream</code>
class, note especially the use of the member <a name="an677"></a>
<code>seekg()</code>:
    <pre>
    #include &lt;iostream&gt;
    #include &lt;string&gt;
    #include &lt;sstream&gt;

    using namespace std;

    int main()
    {
        istringstream istr("123 345");  // store some text.
        int x;

        istr.seekg(2);              // skip "12"
        istr &gt;&gt; x;                  // extract int
        cout &lt;&lt; x &lt;&lt; endl;          // write it out
        istr.seekg(0);              // retry from the beginning
        istr &gt;&gt; x;                  // extract int
        cout &lt;&lt; x &lt;&lt; endl;          // write it out
        istr.str("666");            // store another text
        istr &gt;&gt; x;                  // extract it
        cout &lt;&lt; x &lt;&lt; endl;          // write it out
    }
    /*
        output of this program:
    3
    123
    666
    */
</pre>
<p>
<a name="MANIPULATORS"></a><a name="l84"></a>
<h2>5.6: Manipulators</h2>
<a name="iostreams/manipulators"></a><code>Ios</code> objects define a set of <em>format flags</em> that are used for determining
the way values are inserted (see section <a href="cplusplus05.html#FORMATFLAGS">5.3.2.1</a>).  The format flags
can be controlled by member functions (see section <a href="cplusplus05.html#FORMATMEMBERS">5.3.2.2</a>), but
also by <a name="an678"></a>
<em>manipulators</em>.  Manipulators are <em>inserted</em> into output streams
or extracted from input streams, instead of being activated through the member
selection operator (`<code>.</code>').
<p>
Manipulators are functions.  New manipulators can be constructed as well. The
construction of manipulators is covered in section <a href="cplusplus09.html#MANIPCONSTRUCTION">9.10.1</a>. In
this section the manipulators that are available in the <strong>C++</strong> I/O library
are discussed. Most manipulators affect <a name="an679"></a>
<em>format flags</em>. See section
<a href="cplusplus05.html#FORMATFLAGS">5.3.2.1</a> for details about these flags. Most manipulators are
parameterless. Sources in which manipulators expecting arguments are used, must
do:
    <a name="an680"></a>

        <pre>
    #include &lt;iomanip&gt;
</pre>
<p>
<ul>
    <li><a name="an681"></a>
<code>std::boolalpha</code>:
        <blockquote>This manipulator will set the <code>ios::boolalpha</code> flag.</blockquote>
    <li><a name="an682"></a>
<code>std::dec</code>:
        <blockquote>This manipulator enforces the display and reading of integral
numbers in <a name="an683"></a>
decimal format. This is the default conversion. The conversion
is applied to values inserted into the stream after processing the
manipulators. For example (see also <code>std::hex</code> and <code>std::oct</code>, below):
        <pre>
    cout &lt;&lt; 16 &lt;&lt; ", " &lt;&lt; hex &lt;&lt; 16 &lt;&lt; ", " &lt;&lt; oct &lt;&lt; 16;
    // produces the output:
    16, 10, 20
</pre>
</blockquote>
    <li><a name="an684"></a>
<code>std::endl</code>:
        <blockquote>This manipulator will insert a newline character into an output
buffer and will flush the buffer thereafter.</blockquote>
    <li><a name="an685"></a>
<code>std::ends</code>:
        <blockquote>This manipulator will insert a string termination character
into an output buffer.</blockquote>
    <li><a name="an686"></a>
<code>std::fixed</code>:
        <blockquote>This manipulator will set the <code>ios::fixed</code> flag.</blockquote>
    <li><a name="an687"></a>
<code>std::flush</code>:
        <blockquote>This manipulator will flush an output buffer.</blockquote>
    <li><a name="an688"></a>
<code>std::hex</code>:
        <blockquote>This manipulator enforces the display and reading of integral
numbers in <a name="an689"></a>
hexadecimal format.</blockquote>
    <li><a name="an690"></a>
<code>std::internal</code>:
        <blockquote>This manipulator will set the <code>ios::internal</code> flag.</blockquote>
    <li><a name="an691"></a>
<code>std::left</code>:
        <blockquote>This manipulator will align values to the left in wide fields.</blockquote>
    <li><a name="an692"></a>
<code>std::noboolalpha</code>:
        <blockquote>This manipulator will clear the <code>ios::boolalpha</code> flag.</blockquote>
    <li><a name="an693"></a>
<code>std::noshowpoint</code>:
        <blockquote>This manipulator will clear the <code>ios::showpoint</code> flag.</blockquote>
    <li><a name="an694"></a>
<code>std::noshowpos</code>:
        <blockquote>This manipulator will clear the <code>ios::showpos</code> flag.</blockquote>
    <li><a name="an695"></a>
<code>std::noshowbase</code>:
        <blockquote>This manipulator will clear the <code>ios::showbase</code> flag.</blockquote>
    <li><a name="an696"></a>
<code>std::noskipws</code>:
        <blockquote>This manipulator will clear the <code>ios::skipws</code> flag.</blockquote>
    <li><a name="an697"></a>
<code>std::nounitbuf</code>:
        <blockquote>This manipulator will stop flushing an output stream after each
write operation. Now the <a name="an698"></a>
 stream is flushed at a
<code>flush</code>, <code>endl</code>, <code>unitbuf</code> or when it is closed.</blockquote>
    <li><a name="an699"></a>
<code>std::nouppercase</code>:
        <blockquote>This manipulator will clear the <code>ios::uppercase</code> flag.</blockquote>
    <li><a name="an700"></a>
<code>std::oct</code>:
        <blockquote>This manipulator enforces the display and reading of integral
numbers in <a name="an701"></a>
octal format.</blockquote>
    <li><a name="an702"></a>
<code>std::resetiosflags(flags)</code>:<blockquote>This manipulator
calls <code>std::resetf(flags)</code> to clear the indicated flag values.</blockquote>
    <li><a name="an703"></a>
<code>std::right</code>:
        <blockquote>This manipulator will align values to the right in wide fields.</blockquote>
    <li><a name="an704"></a>
<code>std::scientific</code>:
        <blockquote>This manipulator will set the <code>ios::scientific</code> flag.</blockquote>
    <li><a name="an705"></a>
<code>std::setbase(int b)</code>:
        <blockquote>This manipulator can be used to display integral values using
the base 8, 10 or 16. It can be used as an alternative to <code>oct, dec, hex</code> in
situations where the base of integral values is parameterized.</blockquote>
    <li><a name="an706"></a>
<code>std::setfill(int ch)</code>:
        <blockquote>This manipulator defines
the filling character in situations where the values of numbers are too small
to fill the width that is used to display these values. By default the blank
space is used.</blockquote>
    <li><a name="an707"></a>
<code>std::setiosflags(flags)</code>:<blockquote>This manipulator calls
<code>std::setf(flags)</code> to set the indicated flag values.</blockquote>
    <li><a name="an708"></a>
<code>std::setprecision(int width)</code>:
        <blockquote>This manipulator will set the precision in which a <code>float</code> or
<code>double</code> is displayed. In combination with <code>std::fixed</code> it can be used to
display a fixed number of digits of the fractional part of a floating or
double value:
            <pre>
    cout &lt;&lt; fixed &lt;&lt; setprecision(3) &lt;&lt; 5.0 &lt;&lt; endl;
    // displays: 5.000
</pre>
        </blockquote>
    <li><a name="an709"></a>
<code>std::setw(int width)</code>:
        <blockquote>This manipulator expects as its argument the width of the field
that is inserted or extracted next. It can be used as manipulator for
insertion, where it defines the maximum number of characters that are
displayed for the field, but it can also be used during
    <a name="an710"></a>
 extraction, where it defines the maximum
number of characters that are inserted into an array of characters.  To
prevent <a name="an711"></a>
array bounds overflow when extracting from <code>cin</code>, <code>setw()</code> can
be used as well:
        <pre>
    cin &gt;&gt; setw(sizeof(array)) &gt;&gt; array;
</pre>
    A nice feature is that a long string appearing at <code>cin</code> is split
into substrings of at most <code>sizeof(array) - 1</code> characters, and that
an <a name="an712"></a>
<code>ASCII-Z</code> character is automatically appended.
    Notes:
        <ul>
        <li><code>setw()</code> is valid <em>only</em> for the next field. It does <em>not</em> act
like e.g., <code>hex</code> which changes the general state of the output stream for
displaying numbers.
        <li> When <code>setw(sizeof(someArray))</code> is used, make sure that
<code>someArray</code> really is an array, and not a pointer to an array: the size of a
pointer, being, e.g., four bytes, is usually not the size of the array that it
points to....
        </ul></blockquote>
    <li><a name="an713"></a>
<code>std::showbase</code>:
        <blockquote>This manipulator will set the <code>ios::showbase</code> flag.</blockquote>
    <li><a name="an714"></a>
<code>std::showpoint</code>:
        <blockquote>This manipulator will set the <code>ios::showpoint</code> flag.</blockquote>
    <li><a name="an715"></a>
<code>std::showpos</code>:
        <blockquote>This manipulator will set the <code>ios::showpos</code> flag.</blockquote>
    <li><a name="an716"></a>
<code>std::skipws</code>:
        <blockquote>This manipulator will set the <code>ios::skipws</code> flag.</blockquote>
    <li><a name="an717"></a>
<code>std::unitbuf</code>:
        <blockquote>This manipulator will flush an output stream  after each write
operation.</blockquote>
    <li><a name="an718"></a>
<code>std::uppercase</code>:
        <blockquote>This manipulator will set the <code>ios::uppercase</code> flag.</blockquote>
    <li><a name="an719"></a>
<code>std::ws</code>:
        <blockquote>This manipulator will remove all whitespace characters that are
available at the current read-position of an input buffer.</blockquote>
    </ul>
<p>
<a name="STREAMBUF"></a><a name="l85"></a>
<h2>5.7: The `streambuf' class</h2>
<a name="iostreams/streambuf"></a>The class <a name="an720"></a>
<code>streambuf</code> defines the input and output character sequences that
are processed by streams. Like an <a name="an721"></a>
<code>ios</code> object, a <code>streambuf</code> object is
not directly constructed, but is implied by objects of other classes that are
<em>specializations</em> of the <code>class streambuf</code>.
<p>
The class plays an important role in realizing possibilities that were
available as extensions to the pre-<a name="an722"></a>
ANSI/ISO standard implementations of
<strong>C++</strong>. Although the class cannot be used directly, its members are
introduced here, as the current chapter is the most logical place to introduce
the <code>class streambuf</code>. However, this section of the current chapter assumes
a basic familiarity with the concept of polymorphism, a topic discussed in
detail in chapter <a href="cplusplus14.html#POLYMORPHISM">14</a>. Readers not yet familiar with the concept
of polymorphism may, for the time being, skip this section without loss of
continuity.
<p>
The primary reason for existence of the <code>class streambuf</code>, however, is
to decouple the <code>stream</code> classes from the <a name="an723"></a>
 devices they operate
upon. The rationale here is to use an extra software layer between on the one
hand the classes allowing us to communicate with the device and the
communication between the software and the devices themselves. This implements
a <a name="an724"></a>
<em>chain of command</em> which is seen regularly in <a name="an725"></a>
software design: The
<em>chain of command</em> is considered a generic pattern for the construction of
<a name="an726"></a>
reusable software, encountered also in, e.g., the <a name="an727"></a>
TCP/IP stack. A
<code>streambuf</code> can be considered yet another example of the chain of command
pattern: here the program talks to <code>stream</code> objects, which in turn forward
their requests to <code>streambuf</code> objects, which in turn communicate with the
devices. Thus, as we will see shortly, we are now able to do in user-software
what had to be done via (expensive) system calls before.
<p>
The <code>class streambuf</code> has no public constructor, but does make available
several public member functions. In addition to these public member functions,
several member functions are available to specializing classes only. These
<a name="an728"></a>
<em>protected</em> <em>members</em> are listed in this section for further
reference. In section <a href="cplusplus05.html#FILEBUF">5.7.2</a> below, a particular specialization of the
<code>class streambuf</code> is introduced. Note that all public members of
<code>streambuf</code> discussed here are <em>also</em> available in <code>filebuf</code>.
<p>
In section <a href="cplusplus14.html#POLYSTREAMBUF">14.6</a> the process of constructing specializations
of the <code>class streambuf</code> is discussed, and in chapter <a href="cplusplus20.html#CONCRETE">20</a> several
other implications of using <code>streambuf</code> objects are mentioned. In the
current chapter examples of copying streams, of redirecting streams and and of
reading and writing to streams using the <code>streambuf</code> members of <code>stream</code>
objects are presented (section <a href="cplusplus05.html#ADVANCEDIO">5.8</a>).
<p>
With the <code>class streambuf</code> the following public member functions are
available. The type <a name="an729"></a>
<code>streamsize</code> that is used below may, for all practical
purposes, be considered an <code>unsigned int</code>.
<p>
Public members for <a name="an730"></a>
input operations:
    <ul>
    <li><a name="an731"></a>
<code>streamsize streambuf::in_avail()</code>:<blockquote>This member function returns a lower bound on the number of
        characters that can be read immediately.</blockquote>
    <li><a name="an732"></a>
<code>int streambuf::sbumpc()</code>:<blockquote>This member function returns the next available character or
        <code>EOF</code>. The character is removed from the <code>streambuf</code>
        object. If no input is available, <code>sbumpc()</code> will call the
        (protected) member <a name="an733"></a>

        <code>uflow()</code> (see section <a href="cplusplus05.html#SBPROTECTED">5.7.1</a> below)
        to make new characters available. <code>EOF</code> is returned if no more
        characters are available.</blockquote>
    <li><a name="an734"></a>
<code>int streambuf::sgetc()</code>:<blockquote>This member function returns the next available character or
        <code>EOF</code>. The character is <em>not</em> removed from the <code>streambuf</code>
        object, however.</blockquote>
    <li><a name="an735"></a>
<code>int streambuf::sgetn(char *buffer, streamsize n)</code>:<blockquote>This member function reads <code>n</code> characters from the input buffer,
        and stores them in <code>buffer</code>. The actual number of characters read is
        returned. This member function calls <a name="an736"></a>
 the
        (protected) member <code>xsgetn()</code> (see section <a href="cplusplus05.html#SBPROTECTED">5.7.1</a> below)
        to obtain the requested number of characters.</blockquote>
    <li><a name="an737"></a>
<code>int streambuf::snextc()</code>:<blockquote>This member function removes the current character from the input
        buffer and returns the next available character or
        <code>EOF</code>. The character is <em>not</em> removed from the <code>streambuf</code>
        object, however.</blockquote>
    <li><a name="an738"></a>
<code>int streambuf::sputback(char c)</code>:<blockquote>Inserts <code>c</code> as the next character to read from the <code>streambuf</code>
        object. Caution should be exercised when using this function: often
        there is a maximum of just one character that can be put back.</blockquote>
    <li><a name="an739"></a>
<code>int streambuf::sungetc()</code>:<blockquote>Returns the last character read to the input buffer, to be read again
        at the next input operation.  Caution should be exercised when using
        this function: often there is a maximum of just one character that
        can be put back.</blockquote>
    </ul>
<p>
Public members for <a name="an740"></a>
output operations:
    <ul>
    <li><a name="an741"></a>
<code>int streambuf::pubsync()</code>:<blockquote>Synchronize (i.e., flush) the buffer, by writing any pending
        information available in the <code>streambuf</code>'s buffer to the
        device. Normally used only by specializing classes.</blockquote>
    <li><a name="an742"></a>
<code>int streambuf::sputc(char c)</code>:<blockquote>This member function inserts <code>c</code> into the <code>streambuf</code> object.
        If, after writing the character, the buffer is full, the function
        calls the (protected) member function <a name="an743"></a>

        <code>overflow()</code> to flush the buffer to the device  (see section
        <a href="cplusplus05.html#SBPROTECTED">5.7.1</a> below).</blockquote>
    <li><a name="an744"></a>
<code>int streambuf::sputn(char const *buffer, streamsize n)</code>:<blockquote>This member function inserts <code>n</code> characters from <code>buffer</code> into
        the <code>streambuf</code> object. The actual number of inserted characters
        is returned. This member function calls <a name="an745"></a>
 the
        (protected) member <code>xsputn()</code> (see section <a href="cplusplus05.html#SBPROTECTED">5.7.1</a> below)
        to insert the requested number of characters.</blockquote>
    </ul>
<p>
Public members for miscellaneous operations:
    <ul>
    <li><a name="an746"></a>
<code>pos_type streambuf::pubseekoff(off_type offset, ios::seekdir way,
            ios::openmode mode = ios::in | ios::out)</code>:<blockquote>Reset the offset of the next character to be read or written to
        <code>offset</code>, relative to the standard <a name="an747"></a>
<code>ios::seekdir</code> values
        indicating the direction of the seeking operation. Normally used only
        by specializing classes.</blockquote>
    <li><a name="an748"></a>
<code>pos_type streambuf::pubseekpos(pos_type offset,
            ios::openmode mode = ios::in | ios::out)</code>:<blockquote>Reset the <a name="an749"></a>
absolute position of the next character to be read or
        written to <code>pos</code>. Normally used only by specializing classes.</blockquote>
    <li><a name="an750"></a>
<code>streambuf *streambuf::pubsetbuf(char* buffer, streamsize n)</code>:<blockquote>Define <a name="an751"></a>
<code>buffer</code> as the buffer to be used by the <code>streambuf</code>
        object. Normally used only by specializing classes.</blockquote>
    </ul>
<p>
<a name="SBPROTECTED"></a><a name="l86"></a>
<h3>5.7.1: Protected `streambuf' members</h3>
    <a name="iostreams/protectedstreambuf"></a>The <a name="an752"></a>
<em>protected</em> <em>members</em> of the <code>class</code> <a name="an753"></a>
<code>streambuf</code> are normally not
accessible. However, they are accessible in specializing classes which are
derived from <code>streambuf</code>.  They are important for understanding and using
the <code>class streambuf</code>. Usually there are both protected <a name="an754"></a>
data members and
protected <a name="an755"></a>
member functions defined in the <code>class streambuf</code>. Since using
data members immediately violates the principle of <a name="an756"></a>
<em>encapsulation</em>, these
members are not mentioned here. As the functionality of <code>streambuf</code>, made
available via its member functions, is quite extensive, directly using its
data members is probably hardly ever necessary. This section not even lists
all protected member functions of the <code>class streambuf</code>. Only those member
functions are mentioned that are useful in constructing specializations. The
<code>class streambuf</code> maintains an input- and/or and output buffer, for which
begin-, actual- and end-pointers have been defined, as depicted in figure
<a href="cplusplus05.html#SBBUFFERS">4</a>. In upcoming sections we will refer to this figure repeatedly.
    <a name="SBBUFFERS"></a><p><center><img src="iostreams/sbbuffers.gif" align="bottom" alt="Figure 4 is shown here."/><br>
Figure 4: Input- and output buffer pointers of the class `streambuf'
</center><p><br>

<p>
Protected <a name="an757"></a>
constructor:
    <ul>
    <li><a name="an758"></a>
<code>streambuf::streambuf()</code>:<blockquote>Default (protected) constructor of the <code>class streambuf</code>.</blockquote>
    </ul>
<p>
Several protected member functions are related to <a name="an759"></a>
input operations. The
member functions marked as <code>virtual</code> may be redefined in classes derived
from <code>streambuf</code>. In those cases, the redefined function will be called by
<code>i/ostream</code> objects that received the addresses of such derived class
objects. See chapter <a href="cplusplus14.html#POLYMORPHISM">14</a> for details about virtual member
functions. Here are the protected members:
    <ul>
    <li><a name="an760"></a>
<code>char *streambuf::eback()</code>:<blockquote>For the input buffer the <code>class streambuf</code> maintains three
        pointers: <code>eback()</code> points to the `end of the putback' area:
        characters can safely be put back up to this position. See also figure
        <a href="cplusplus05.html#SBBUFFERS">4</a>. <code>Eback()</code> can be considered to represent the
        <em>beginning</em> of the input buffer.</blockquote>
    <li><a name="an761"></a>
<code>char *streambuf::egptr()</code>:<blockquote>For the input buffer the <code>class streambuf</code> maintains three
        pointers: <code>egptr()</code> points just beyond the last character
        that can be retrieved. See also figure <a href="cplusplus05.html#SBBUFFERS">4</a>. If <code>gptr()</code>
        (see below) equals <code>egptr()</code> the buffer must be refilled. This
        should be realized by calling <code>underflow()</code>, see below.</blockquote>
    <li><a name="an762"></a>
<code>void streambuf::gbump(int n)</code>:<blockquote>This function moves the input pointer over <code>n</code> positions.</blockquote>
    <li><a name="an763"></a>
<code>char *streambuf::gptr()</code>:<blockquote>For the input buffer the <code>class streambuf</code> maintains three
        pointers: <code>gptr()</code> points to the next character to be retrieved. See
        also figure <a href="cplusplus05.html#SBBUFFERS">4</a>.</blockquote>
    <li><a name="an764"></a>
<code>virtual int streambuf::pbackfail(int c)</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to do something intelligent when putting back
        character <code>c</code> fails. One of the things to consider here is to
        restore the old read pointer when putting back a character fails,
        because the beginning of the input buffer is reached. This member
        function is called when ungetting or putting back  a character fails.</blockquote>
    <li><a name="an765"></a>
<code>void streambuf::setg(char *beg, char *next, char *beyond)</code>:<blockquote>This member function initializes an input buffer: <code>beg</code> points to
        the beginning of the input area, <code>next</code> points to the next character
        to be retrieved, and <code>beyond</code> points beyond the last character of
        the input buffer. Ususally <code>next</code> is at least <code>beg + 1</code>, to allow
        for a put back operation. No input buffering is used when this member
        is called with 0-arguments (not <em>no</em> arguments, but arguments having
        0 values.) See also the member <code>streambuf::uflow()</code>, below.</blockquote>
    <li><a name="an766"></a>
<code>virtual streamsize streambuf::showmanyc()</code>:<blockquote>(Pronounce: s-how-many-c) This member function may be redefined by
        specializations of the
        <code>class streambuf</code>. It must return a guaranteed lower bound on the
        number of characters that can be read from the device before
        <code>uflow()</code> or <code>underflow()</code> returns <code>EOF</code>. By default 0 is
        returned (meaning at least 0 characters will be returned before the
        latter two functions will return <code>EOF</code>).</blockquote>
    <li><a name="an767"></a>
<code>virtual int streambuf::uflow()</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to reload an input buffer with new characters. The
        default implementation is to call <code>underflow()</code>, see below, and to
        increment the read pointer <code>gptr()</code>. When no input buffering is
        required this function, rather than <code>underflow()</code> can be
        overridden to produce the next available character from the device to
        read.</blockquote>
    <li><a name="an768"></a>
<code>virtual int streambuf::underflow()</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to read another character from the device. The
        default implementation is to return <code>EOF</code>. When buffering is
        used, often the complete buffer is not refreshed, as this would make
        it impossible to put back characters just after a reload. This system,
        where only a subsection of the input buffer is reloaded,
        is called a <a name="an769"></a>
<em>split buffer</em>.</blockquote>
    <li><a name="an770"></a>
<code>virtual streamsize streambuf::xsgetn(char *buffer, streamsize n)</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to retrieve <code>n</code> characters from the device.
        The default implementation is to call <code>sbumpc()</code> for every single
        character. By default this calls (eventually) <code>underflow()</code> for
        every single character.
        </blockquote>
    </ul>
<p>
Here are the protected member functions related to <a name="an771"></a>
output
operations. Similarly to the functions related to input operations, some of
the following functions are <code>virtual</code>: they may be redefined in derived
classes:
    <ul>
    <li><a name="an772"></a>
<code>virtual int streambuf::overflow(int c)</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to flush the characters in the output buffer to
        the device, and then to reset the output buffer pointers such that the
        buffer may be considered empty. It receives as parameter <code>c</code> the
        next character to be processed by the <code>streambuf</code>. If no output
        buffering is used, <code>overflow()</code> is called for every single character
        which is written to the <code>streambuf</code> object. This is realized by
        setting the buffer pointers (using, e.g., <code>setp()</code>, see below) to
        0. The <a name="an773"></a>
default implementation returns <code>EOF</code>, indicating that
        no characters can be written to the device.</blockquote>
    <li><a name="an774"></a>
<code>char *streambuf::pbase()</code>:<blockquote>For the output buffer the <code>class streambuf</code> maintains three
        pointers: <code>pbase()</code> points to the beginning of the output buffer
        area. See also figure <a href="cplusplus05.html#SBBUFFERS">4</a>.</blockquote>
    <li><a name="an775"></a>
<code>char *streambuf::epptr()</code>:<blockquote>For the output buffer the <code>class streambuf</code> maintains three
        pointers: <code>epptr()</code> points just beyond the location of the
        last character
        that can be written. See also figure <a href="cplusplus05.html#SBBUFFERS">4</a>. If <code>pptr()</code>
        (see below) equals <code>epptr()</code> the buffer must be flushed. This is
        realized by calling <code>overflow()</code>, see below.</blockquote>
    <li><a name="an776"></a>
<code>void streambuf::pbump(int n)</code>:<blockquote>This function moves the output pointer over <code>n</code> positions.</blockquote>
    <li><a name="an777"></a>
<code>char *streambuf::pptr()</code>:<blockquote>For the output buffer the <code>class streambuf</code> maintains three
        pointers: <code>pptr()</code> points to the location of the next character
        to be written. See also figure <a href="cplusplus05.html#SBBUFFERS">4</a>.</blockquote>
    <li><a name="an778"></a>
<code>void streambuf::setp(char *beg, char *beyond)</code>:<blockquote>This member function initializes an output buffer: <code>beg</code> points to
        the beginning of the output area and <code>beyond</code> points beyond the last
        character of the output area. Use 0 for the arguments to indicate that
        <a name="an779"></a>
no buffering is requested. In that case <code>overflow()</code> is called
        for every single character to write to the device.</blockquote>
    <li><a name="an780"></a>
<code>streamsize streambuf::xsputn(char const *buffer, streamsize n)</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to write <code>n</code> characters immediately to the
        device. The actual number of inserted characters should be
        returned. The default implementation calls <code>sputc()</code> for each
        individual character, so redefining is only needed if a more efficient
        implementation is required.</blockquote>
    </ul>
<p>
Protected member functions related to <a name="an781"></a>
buffer management and positioning:
    <ul>
    <li><a name="an782"></a>
<code>virtual streambuf *streambuf::setbuf(char *buffer, streamsize n)</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to install a buffer. The default implementation is
        to do nothing.</blockquote>
    <li><a name="an783"></a>

        <code>virtual
            pos_type streambuf::seekoff(off_type offset,
            ios::seekdir way,</code><br>
            <code>ios::openmode mode = ios::in | ios::out)</code>
       <blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to reset the next pointer for input or output to a
        new <a name="an784"></a>
relative position (using <code>ios::beg, ios::cur</code> or
        <code>ios::end</code>). The default implementation is to indicate <a name="an785"></a>
failure by
        returning -1. The function is called when, e.g., <code>tellg()</code> or
        <code>tellp()</code> is called. When a <code>streambuf</code> specialization supports
        seeking, then the specialization should also define this function to
        determine what to do with a repositioning (or <code>tellp/g()</code>) request.</blockquote>
    <li> <a name="an786"></a>

        <code>virtual pos_type streambuf::seekpos(pos_type offset,
            ios::openmode mode =</code><br><code>ios::in | ios::out)</code>:
       <blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to reset the next pointer for input or output to a
        new <a name="an787"></a>
absolute position (i.e, relative to <code>ios::beg</code>). The default
        implementation is to indicate <a name="an788"></a>
failure by returning -1.</blockquote>
    <li><a name="an789"></a>
<code>virtual int sync()</code>:<blockquote>This member function may be redefined by specializations of the
        <code>class streambuf</code> to
        flush the output buffer to the <a name="an790"></a>
device or to reset the input device
        to the position of the last consumed character. The default
        implementation (not using a buffer) is to return 0, indicating
        successfull syncing. The member
        function is used to make sure that any characters that are still
        buffered are written to the device or to restore unconsumed characters
        to the device when the <code>streambuf</code> object ceases to exist.</blockquote>
   </ul>
    Morale: when specializations of the <code>class streambuf</code> are designed,
the very least thing to do is to redefine <code>underflow()</code> for specializations
aimed at reading information from devices, and to redefine <code>overflow()</code> for
specializations aimed at writing information to devices. Several examples of
specializations of the <code>class streambuf</code> will be given in the <strong>C++</strong>
Annotations (e.g., in chapter <a href="cplusplus20.html#CONCRETE">20</a>).
<p>
Objects of the class <code>fstream</code> use a combined input/output buffer. This
results from the fact that <code>istream</code> and <code>ostream</code>, are virtually derived
from <code>ios</code>, which contains the <code>streambuf</code>. As explained in section
<a href="cplusplus14.html#VIRTUALBASE">14.4.2</a>, this implies that classes derived from both <code>istream</code> and
<code>ostream</code> share their <code>streambuf</code> pointer. In order to construct a class
supporting both input and output on separate buffers, the <code>streambuf</code> itself
may define internally two buffers. When <code>seekoff()</code> is called for reading,
its <code>mode</code> parameter is set to <code>ios::in</code>, otherwise to <code>ios::out</code>. This
way, the <code>streambuf</code> specializaiton knows whether it should access the
<code>read</code> buffer or the <code>write</code> buffer. Of course, <code>underflow()</code> and
<code>overflow()</code> themselves already know on which buffer they should operate.
<p>
<a name="FILEBUF"></a><a name="l87"></a>
<h3>5.7.2: The class `filebuf'</h3>
    <a name="iostreams/filebuf"></a>The <code>class</code> <a name="an791"></a>
<code>filebuf</code> is a specialization of <a name="an792"></a>
<code>streambuf</code> used by the
file <a name="an793"></a>
<code>stream</code> classes. Apart from the (public) members that are available
through the <code>class streambuf</code>, it defines the following extra (public)
members:
    <ul>
    <li><a name="an794"></a>
<code>filebuf::filebuf()</code>:<blockquote>Since the class has a constructor, it is, different from the <code>class
        streambuf</code>,  possible to construct a <code>filebuf</code> object. This defines
        a plain <code>filebuf</code> object, not yet connected to a stream.</blockquote>
    <li><a name="an795"></a>
<code>bool filebuf::is_open()</code>:<blockquote>This member function returns <code>true</code> if the <code>filebuf</code> is actually
        connected to an open file. See the <code>open()</code> member, below.</blockquote>
    <li><a name="an796"></a>
<code>filebuf *filebuf::open(char const *name, ios::openmode mode)</code>:<blockquote>This member function associates the <code>filebuf</code> object with
        a file whose name is provided. The file is opened according to
        the provided <a name="an797"></a>
<code>ios::openmode</code>.</blockquote>
    <li><a name="an798"></a>
<code>filebuf *filebuf::close()</code>:<blockquote>This member function closes the association between
        the <code>filebuf</code> object and its file. The association is automatically
        closed when the <code>filebuf</code> object ceases to exist.</blockquote>
    </ul>
    Before <code>filebuf</code> objects can be defined the following preprocessor
directive must have been specified: <a name="an799"></a>

        <pre>
    #include &lt;fstream&gt;
</pre>
<p>
<a name="ADVANCEDIO"></a><a name="l88"></a>
<h2>5.8: Advanced topics</h2>
<p>
<a name="CPSTREAM"></a><a name="l89"></a>
<h3>5.8.1: Copying streams</h3>
    <a name="iostreams/copying"></a>Usually, files are copied <a name="an800"></a>
 either by reading a source file
character by character or line by line. The basic <em>mold</em> for
    <a name="an801"></a>
processing files is as follows:
        <ul>
            <li> In an eternal loop:
            <ol>
                <li> read a character
                <li> if reading did not succeed (i.e., <code>fail()</code> returns
                        true), <code>break</code> from the loop
                <li> process the character
            </ol>
        </ul>
    It is important to note that the reading must <em>precede</em> the testing, as
it is only possible to know after the actual attempt to read from a file
whether the reading succeeded or not. Of course, variations are possible:
<code>getline(istream &amp;, string &amp;)</code> (see section <a href="cplusplus05.html#ISTREAMREAD">5.5.1.1</a>) returns an
<code>istream &amp;</code> itself, so here reading and testing may be realized in one
expression. Nevertheless, the above mold represents the general case. So,
the following program could be used to copy <code>cin</code> to <code>cout</code>:
        <pre>
#include &lt;iostream&gt;

using namespace::std;

int main()
{
    while (true)
    {
        char c;

        cin.get(c);
        if (cin.fail())
            break;
        cout &lt;&lt; c;
    }
    return 0;
}
</pre>
<p>
By combining the <code>get()</code> with the <code>if</code>-statement a construction
comparable to <code>getline()</code> could be used:
        <pre>
    if (!cin.get(c))
        break;
</pre>
Note, however, that this would still follow the basic rule:
    `<a name="an802"></a>
read first, test later'.
<p>
This simple copying of a file, however, isn't required very often. More
often, a situation is encountered where a file is processed up to a certain
point, whereafter the remainder of the file can be copied unaltered. The
following program illustrates this situation: the <code>ignore()</code> call is used to
skip the first line (for the sake of the example it is assumed that the first
line is at most 80 characters long), the second statement uses a special
overloaded version of the <<-operator, in which a <a name="an803"></a>
<code>streambuf</code> pointer
<a name="an804"></a>
 is inserted into another stream. As the member
<code>rdbuf()</code> returns a <code>streambuf *</code>, it can thereupon be inserted into
<code>cout</code>. This immediately copies the remainder of <code>cin</code> to <code>cout</code>:
        <pre>
    #include &lt;iostream&gt;
    using namespace std;

    int main()
    {
        cin.ignore(80, '\n');   // skip the first line
        cout &lt;&lt; cin.rdbuf();    // copy the rest by inserting a streambuf *
    }
</pre>
    Note that this method assumes a <code>streambuf</code> object, so it will work for
all specializations of <code>streambuf</code>. Consequently, if the <code>class streambuf</code>
is specialized for a particular <a name="an805"></a>
device it can be inserted into any other
stream using the above method.
<p>
<a name="COUPLING"></a><a name="l90"></a>
<h3>5.8.2: Coupling streams</h3>
    <a name="iostreams/coupling"></a>Ostreams <a name="an806"></a>
 can be <em>coupled</em> to <a name="an807"></a>
<code>ios</code> objects using the
<a name="an808"></a>
<code>tie()</code> member function. This results in flushing all buffered output of the
<code>ostream</code> object (by calling <code>flush()</code>) whenever an <a name="an809"></a>
input or <a name="an810"></a>
output
operation is performed on the <code>ios</code> object to which the <code>ostream</code> object
is tied.  By default <a name="an811"></a>
<code>cout</code> is tied to <a name="an812"></a>
<code>cin</code> (i.e., <code>cin.tie(cout)</code>):
whenever an operation on <code>cin</code> is requested, <code>cout</code> is flushed first. To
break the coupling, the member function <code>ios::tie(0)</code> can be called.
<p>
Another (frequently useful, but non-default) example of coupling streams is to
tie <a name="an813"></a>
<code>cerr</code> to <a name="an814"></a>
<code>cout</code>: this way standard output and error messages written
to the screen will appear in sync with the time at which they were generated:
    <pre>
    #include &lt;iostream&gt;
    using namespace std;

    int main()
    {
        cout &lt;&lt; "first (buffered) line to cout ";
        cerr &lt;&lt; "first (unbuffered) line to cerr\n";
        cout &lt;&lt; "\n";

        cerr.tie(&amp;cout);

        cout &lt;&lt; "second (buffered) line to cout ";
        cerr &lt;&lt; "second (unbuffered) line to cerr\n";
        cout &lt;&lt; "\n";
    }
    /*
        Generated output:

    first (buffered) line to cout
    first (unbuffered) line to cerr
    second (buffered) line to cout second (unbuffered) line to cerr

    */
</pre>
<p>
An alternative way to couple streams is to make streams use a common
<code>streambuf</code> object. This can be realized using the <a name="an815"></a>

<code>ios::rdbuf(streambuf *)</code> member function. This way two streams can use,
e.g. their own formatting, one stream can be used for input, the other for
output, and redirection using the iostream library rather than operating
system calls can be realized. See the next sections for examples.
<p>
<a name="REDIR"></a><a name="l91"></a>
<h3>5.8.3: Redirecting streams</h3>
    <a name="iostreams/redirection"></a>By using the <a name="an816"></a>
<code>ios::rdbuf()</code> member streams can share their <code>streambuf</code>
objects. This means that the information that is written to a stream will
actually be written to another stream, a phenomenon normally called
<a name="an817"></a>
<em>redirection</em>. Redirection is normally realized at the level of the
operating system, and in some situations that is still necessary (see section
<a href="cplusplus20.html#REDIRECTION">20.3.1</a>).
<p>
A standard situation where redirection is wanted is to write error messages to
file rather than to standard error, usually indicated by its
    <a name="an818"></a>
file descriptor number 2. In the <a name="an819"></a>
Unix operating system using the
<a name="an820"></a>
<code>bash</code> shell, this can be realized as follows:
        <pre>
    program 2&gt;/tmp/error.log
</pre>
    With this command any error messages written by <code>program</code> will be saved
on the file <code>/tmp/error.log</code>, rather than being written to the screen.
<p>
Here is how this can be realized using <code>streambuf</code> objects. Assume
<code>program</code> now expects an optional argument defining the name of the file to
write the error messages to; so <code>program</code> is now called as:
        <pre>
    program /tmp/error.log
</pre>
    Here is the example realizing redirection. It is annotated below.
        <pre>
    #include &lt;iostream&gt;
    #include &lt;streambuf&gt;
    #include &lt;fstream&gt;

    using namespace std;

    int main(int argc, char **argv)
    {
        ofstream errlog;                                // 1
        streambuf *cerr_buffer = 0;                     // 2

        if (argc == 2)
        {
            errlog.open(argv[1]);                       // 3
            cerr_buffer = cerr.rdbuf(errlog.rdbuf());   // 4
        }
        else
        {
            cerr &lt;&lt; "Missing log filename\n";
            return 1;
        }

        cerr &lt;&lt; "Several messages to stderr, msg 1\n";
        cerr &lt;&lt; "Several messages to stderr, msg 2\n";

        cout &lt;&lt; "Now inspect the contents of " &lt;&lt;
                argv[1] &lt;&lt; "... [Enter] ";
        cin.get();                                      // 5

        cerr &lt;&lt; "Several messages to stderr, msg 3\n";

        cerr.rdbuf(cerr_buffer);                        // 6
        cerr &lt;&lt; "Done\n";                               // 7
    }
    /*
        Generated output on file argv[1]

        at cin.get():

    Several messages to stderr, msg 1
    Several messages to stderr, msg 2

        at the end of the program:

    Several messages to stderr, msg 1
    Several messages to stderr, msg 2
    Several messages to stderr, msg 3
    */
</pre>
    <ul>
    <li> At lines 1-2 local variables are defined: <code>errlog</code> is the
<code>ofstream</code> to write the error messages too, and <code>cerr_buffer</code> is a pointer
to a <code>streambuf</code>, to point to the original <code>cerr</code> buffer. This is further
discussed below.
    <li> At line 3  the alternate error stream is opened.
    <li> At line 4  the redirection takes place: <code>cerr</code> will now write to
the <code>streambuf</code> defined by <code>errlog</code>. It is important that
the original buffer used by <code>cerr</code> is saved, as explained below.
    <li> At line 5  we pause. At this point, two lines were written to
the alternate error file. We get a chance to take a look at its contents:
there were indeed two lines written to the file.
    <li> At line 6  the redirection is terminated. This is very important, as
the <code>errlog</code> object is destroyed at the end of <code>main()</code>. If <code>cerr</code>'s
buffer would not have been restored, then at that point
<code>cerr</code> would refer to a non-existing <code>streambuf</code> object, which might
produce unexpected results. It is the <a name="an821"></a>
responsibility of the programmer to
make sure that an original <code>streambuf</code> is saved before redirection, and is
restored when the redirection ends.
    <li> Finally, at line 7, <code>Done</code> is now written to the screen again, as
the redirection has been terminated.
    </ul>
<p>
<a name="FSTREAM"></a><a name="l92"></a>
<h3>5.8.4: Reading AND Writing streams</h3>
    <a name="iostreams/readwrite"></a>In order to both <a name="an822"></a>
read and write to a stream an <a name="an823"></a>
<code>fstream</code> object
must be created.  As with <code>ifstream</code> and <code>ofstream</code> objects, its
constructor receives the name of the file to be opened:
        <pre>
        fstream inout("iofile", ios::in | ios::out);
</pre>
    Note the use of the <a name="an824"></a>
<code>ios</code> constants <a name="an825"></a>
<code>ios::in</code> and <a name="an826"></a>
<code>ios::out</code>,
indicating that the file must be opened for both reading and writing. Multiple
mode indicators may be used, concatenated by the binary or operator <code>'|'</code>.
Alternatively, instead of <code>ios::out</code>, <a name="an827"></a>
<code>ios::app</code> could have been used, in
which case writing will always be done at the end of the file.
<p>
Somehow reading and writing to a file is a bit awkward: what to do when
the file may or may not exist yet, but if it already exists it should not be
rewritten? <a name="an828"></a>

    <a name="an829"></a>

    I have been fighting with this problem for some time, and now I use
the following approach:
    <pre>
    #include &lt;fstream&gt;
    #include &lt;iostream&gt;
    #include &lt;string&gt;

    using namespace std;

    int main()
    {
        fstream rw("fname", ios::out | ios::in);
        if (!rw)
        {
            rw.clear();
            rw.open("fname", ios::out | ios::trunc | ios::in);
        }
        if (!rw)
        {
            cerr &lt;&lt; "Opening `fname' failed miserably" &lt;&lt; endl;
            return 1;
        }

        cerr &lt;&lt; rw.tellp() &lt;&lt; endl;

        rw &lt;&lt; "Hello world" &lt;&lt; endl;
        rw.seekg(0);

        string s;
        getline(rw, s);

        cout &lt;&lt; "Read: " &lt;&lt; s &lt;&lt; endl;
    }
</pre>
    In the above example, the constructor fails when <code>fname</code> doesn't exist
yet. However, in that case the <code>open()</code> member will normally succeed since
the file is created due to the <code>ios::trunc</code> flag. If the file already
existed, the constructor will succeed. If the <a name="an830"></a>
<code>ios::ate</code> flag would have
been specified as well with <code>rw</code>'s initial construction, the first
read/write action would by default have take place at <code>EOF</code>. However,
<code>ios::ate</code> is not <a name="an831"></a>
<code>ios::app</code>, so it would then still have been possible to
repositioned <code>rw</code> using <code>seekg()</code> or <code>seekp()</code>.
<p>
Under <a name="an832"></a>
 <a name="an833"></a>
 <a name="an834"></a>
 <a name="an835"></a>
 <strong>DOS</strong>-like operating
systems, which use the multiple character <code>\r\n</code> sentinels to separate lines
in <a name="an836"></a>
text files the flag <a name="an837"></a>
<code>ios::binary</code> is required for
processing <a name="an838"></a>
binary files to ensure that <code>\r\n</code> combinations are processed
as two characters.
<p>
With <code>fstream</code> objects, combinations of file flags are used to make sure
that a stream is or is not (re)created empty when opened. See section
<a href="cplusplus05.html#OUTPUTMODES">5.4.2.1</a> for details.
<p>
Once a file has been opened in read and write mode, the << operator
can be used to insert information to the file, while the >> operator may
be used to extract information from the file. These operations may be
performed in random order.  The following fragment will read a blank-delimited
word from the file, and will then write a string to the file, just beyond the
point where the string just read terminated, followed by the reading of yet
another string just beyond the location where the string just written ended:
        <pre>
    fstream f("filename", ios::in | ios::out | ios::trunc);
    string  str;

    f &gt;&gt; str;       // read the first word
                    // write a well known text
    f &lt;&lt; "hello world";
    f &gt;&gt; str;       // and read again
</pre>
    Since the operators << and >> can apparently be used with
<code>fstream</code> objects, you might wonder whether a series of << and >>
operators in one statement might be possible. After all, <code>f</code> >> <code>str</code>
should produce an <code>fstream &amp;</code>, shouldn't it?
<p>
The answer is: it doesn't. The compiler casts the <code>fstream</code> object into
an <a name="an839"></a>
<code>ifstream</code> object in combination with the extraction operator, and into
an <a name="an840"></a>
<code>ofstream</code> object in combination with the insertion
operator. Consequently, a statement like
        <pre>
    f &gt;&gt; str &lt;&lt; "grandpa" &gt;&gt; str;
</pre>
    results in a compiler error like
        <pre>
    no match for `operator &lt;&lt;(class istream, char[8])'
</pre>
    Since the compiler complains about the <code>istream</code> class, the <code>fstream</code>
object is apparently considered an <code>ifstream</code> object in combination with the
extraction operator.
<p>
Of course, random insertions and extractions are hardly used. Generally,
insertions and extractions take place at specific locations in the file.
In those cases, the position where the insertion or extraction must take
place can be controlled and monitored by the <a name="an841"></a>
<code>seekg()</code> and <a name="an842"></a>
<code>tellg()</code>
member functions (see sections <a href="cplusplus05.html#OSTREAMPOS">5.4.1.2</a> and <a href="cplusplus05.html#ISTREAMPOS">5.5.1.2</a>).
<p>
Error conditions (see section <a href="cplusplus05.html#IOSTATES">5.3.1</a>) occurring due to, e.g., reading
beyond end of file, reaching end of file, or positioning before begin of file,
can be cleared using the <a name="an843"></a>
<code>clear()</code> member function.  Following <code>clear()</code>
processing may continue. E.g.,
        <pre>
    fstream f("filename", ios::in | ios::out | ios::trunc);
    string  str;

    f.seekg(-10);   // this fails, but...
    f.clear();      // processing f continues

    f &gt;&gt; str;       // read the first word
</pre>
    A common situation in which files are both read and written occurs in
    <a name="an844"></a>
<em>data base</em> applications, where files consists of records of fixed
size, and where the location and size of pieces of information is well
known. For example, the following program may be used to add lines of text to
a (possibly existing) file, and to retrieve a certain line, based on its
order-numer from the file. Note the use of the <a name="an845"></a>
<em>binary file</em> <code>index</code> to
retrieve the location of the first byte of a line.
        <pre>
    #include &lt;iostream&gt;
    #include &lt;fstream&gt;
    #include &lt;string&gt;
    using namespace std;

    void err(char const *msg)
    {
        cout &lt;&lt; msg &lt;&lt; endl;
        return;
    }

    void err(char const *msg, long value)
    {
        cout &lt;&lt; msg &lt;&lt; value &lt;&lt; endl;
        return;
    }

    void read(fstream &amp;index, fstream &amp;strings)
    {
        int idx;

        if (!(cin &gt;&gt; idx))                          // read index
            return err("line number expected");

        index.seekg(idx * sizeof(long));            // go to index-offset

        long offset;

        if
        (
            !index.read                             // read the line-offset
            (
                reinterpret_cast&lt;char *&gt;(&amp;offset),
                sizeof(long)
            )
        )
            return err("no offset for line", idx);

        if (!strings.seekg(offset))                 // go to the line's offset
            return err("can't get string offet ", offset);

        string line;

        if (!getline(strings, line))                // read the line
            return err("no line at ", offset);

        cout &lt;&lt; "Got line: " &lt;&lt; line &lt;&lt; endl;       // show the line
    }


    void write(fstream &amp;index, fstream &amp;strings)
    {
        string line;

        if (!getline(cin, line))                  // read the line
            return err("line missing");

        strings.seekp(0, ios::end);               // to strings
        index.seekp(0, ios::end);                 // to index

        long offset = strings.tellp();

        if
        (
            !index.write                          // write the offset to index
            (
                reinterpret_cast&lt;char *&gt;(&amp;offset),
                sizeof(long)
            )
        )
            err("Writing failed to index: ", offset);

        if (!(strings &lt;&lt; line &lt;&lt; endl))           // write the line itself
            err("Writing to `strings' failed");
                                                  // confirm writing the line
        cout &lt;&lt; "Write at offset " &lt;&lt; offset &lt;&lt; " line: " &lt;&lt; line &lt;&lt; endl;
    }

    int main()
    {
        fstream index("index", ios::trunc | ios::in | ios::out);
        fstream strings("strings", ios::trunc | ios::in | ios::out);

        cout &lt;&lt; "enter `r &lt;number&gt;' to read line &lt;number&gt; or "
                                    "w &lt;line&gt;' to write a line\n"
                "or enter `q' to quit.\n";

        while (true)
        {
            cout &lt;&lt; "r &lt;nr&gt;, w &lt;line&gt;, q ? ";       // show prompt

            string cmd;

            cin &gt;&gt; cmd;                             // read cmd

            if (cmd == "q")                         // process the cmd.
                return 0;

            if (cmd == "r")
                read(index, strings);
            else if (cmd == "w")
                write(index, strings);
            else
                cout &lt;&lt; "Unknown command: " &lt;&lt; cmd &lt;&lt; endl;
        }
    }
</pre>
    As another example of reading and writing files, consider the following
program, which also serves as an illustration of reading an <a name="an846"></a>
ASCII-Z
delimited string:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;fstream&gt;
    using namespace std;

    int main()
    {                                       // r/w the file
        fstream f("hello", ios::in | ios::out | ios::trunc);

        f.write("hello", 6);                // write 2 ascii-z
        f.write("hello", 6);

        f.seekg(0, ios::beg);               // reset to begin of file

        char buffer[100];                   // or: char *buffer = new char[100]
        char c;
                                            // read the first `hello'
        cout &lt;&lt; f.get(buffer, sizeof(buffer), 0).tellg() &lt;&lt; endl;;
        f &gt;&gt; c;                             // read the ascii-z delim

                                            // and read the second `hello'
        cout &lt;&lt; f.get(buffer + 6, sizeof(buffer) - 6, 0).tellg() &lt;&lt; endl;

        buffer[5] = ' ';                    // change asciiz to ' '
        cout &lt;&lt; buffer &lt;&lt; endl;             // show 2 times `hello'
    }
    /*
        Generated output:
    5
    11
    hello hello
    */
</pre>
<p>
A completely different way to both read and write to streams can be
implemented using the <a name="an847"></a>
<code>streambuf</code> members of stream objects. All
considerations mentioned so far remain valid: before a read operation
following a write operation <code>seekg()</code> must be used, and before a write
operation following a read operation <code>seekp()</code> must be used. When the
stream's <code>streambuf</code> objects are used, either an <code>istream</code> is associated
with the <code>streambuf</code> object of another <code>ostream</code> object, or <em>vice
versa</em>, an <code>ostream</code> object is associated with the <code>streambuf</code> object of
another <code>istream</code> object. Here is the same program as before, now using
    <a name="an848"></a>
 <em>associated streams</em>:
        <pre>
    #include &lt;iostream&gt;
    #include &lt;fstream&gt;
    #include &lt;string&gt;
    using namespace std;

    void err(char const *msg)
    {
        cout &lt;&lt; msg &lt;&lt; endl;
        return;
    }

    void err(char const *msg, long value)
    {
        cout &lt;&lt; msg &lt;&lt; value &lt;&lt; endl;
        return;
    }

    void read(istream &amp;index, istream &amp;strings)
    {
        int idx;

        if (!(cin &gt;&gt; idx))                          // read index
            return err("line number expected");

        index.seekg(idx * sizeof(long));            // go to index-offset

        long offset;

        if
        (
            !index.read                             // read the line-offset
            (
                reinterpret_cast&lt;char *&gt;(&amp;offset),
                sizeof(long)
            )
        )
            return err("no offset for line", idx);

        if (!strings.seekg(offset))                 // go to the line's offset
            return err("can't get string offet ", offset);

        string line;

        if (!getline(strings, line))                // read the line
            return err("no line at ", offset);

        cout &lt;&lt; "Got line: " &lt;&lt; line &lt;&lt; endl;       // show the line
    }


    void write(ostream &amp;index, ostream &amp;strings)
    {
        string line;

        if (!getline(cin, line))                  // read the line
            return err("line missing");

        strings.seekp(0, ios::end);               // to strings
        index.seekp(0, ios::end);                 // to index

        long offset = strings.tellp();

        if
        (
            !index.write                          // write the offset to index
            (
                reinterpret_cast&lt;char *&gt;(&amp;offset),
                sizeof(long)
            )
        )
            err("Writing failed to index: ", offset);

        if (!(strings &lt;&lt; line &lt;&lt; endl))           // write the line itself
            err("Writing to `strings' failed");
                                                  // confirm writing the line
        cout &lt;&lt; "Write at offset " &lt;&lt; offset &lt;&lt; " line: " &lt;&lt; line &lt;&lt; endl;
    }

    int main()
    {
        ifstream index_in("index", ios::trunc | ios::in | ios::out);
        ifstream strings_in("strings", ios::trunc | ios::in | ios::out);
        ostream  index_out(index_in.rdbuf());
        ostream  strings_out(strings_in.rdbuf());

        cout &lt;&lt; "enter `r &lt;number&gt;' to read line &lt;number&gt; or "
                                    "w &lt;line&gt;' to write a line\n"
                "or enter `q' to quit.\n";

        while (true)
        {
            cout &lt;&lt; "r &lt;nr&gt;, w &lt;line&gt;, q ? ";       // show prompt

            string cmd;

            cin &gt;&gt; cmd;                             // read cmd

            if (cmd == "q")                         // process the cmd.
                return 0;

            if (cmd == "r")
                read(index_in, strings_in);
            else if (cmd == "w")
                write(index_out, strings_out);
            else
                cout &lt;&lt; "Unknown command: " &lt;&lt; cmd &lt;&lt; endl;
        }
    }
</pre>
    Please note:
    <ul>
    <li> The streams to associate with the <code>streambuf</code> objects of
existing streams are not <a name="an849"></a>
<code>ifstream</code> or <a name="an850"></a>
<code>ofstream</code> objects (or, for that
matter, <code>istringstream</code> or <code>ostringstream</code> objects), but basic
<a name="an851"></a>
<code>istream</code> and <a name="an852"></a>
<code>ostream</code> objects.
    <li> The <code>streambuf</code> object does not have to be defined in an
<code>ifstream</code> or <a name="an853"></a>
<code>ofstream</code> object: it can be defined outside of the streams,
using constructions like:
        <pre>
    filebuf fb("index", ios::in | ios::out | ios::trunc);
    istream index_in(&amp;fb);
    ostream index_out(&amp;fb);
</pre>
    <li> Note that an <code>ifstream</code> object can be constructed using stream
modes normally used for writing to files. Conversely, <code>ofstream</code> objects can
be constructed using stream modes normally used for reading from files.
    <li> If <code>istream</code> and <code>ostreams</code> are associated through a common
<code>streambuf</code>, then the read and write pointers (should) point to the same
locations: they are tightly coupled.
    <li> The advantage of using a separate <code>streambuf</code> over a predefined
<code>fstream</code> object is (of course) that it opens the possibility of using
<code>stream</code> objects with specialized <code>streambuf</code> objects. These <code>streambuf</code>
objects may then specifically be constructed to interface particular
devices. Elaborating this is left as an <a name="an854"></a>
exercise to the reader.
    </ul>
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus04.html">Previous Chapter</a>
    <li> <a href="cplusplus06.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
